iOS自定义UIButton未出现在视图中

时间:2014-03-10 23:08:33

标签: ios objective-c view uibutton drawrect

我遇到了覆盖UIButton类并自定义它的问题。

我有一个使用UIButton类的块类:

#import "Block.h"

@implementation Block

-(id)initWithWidth:(int)width withHeight:(int)height withXPos:(double)x withYPos:(double)y{
    _width=width;
    _height=height;
    _x=x;
    _y=y;
    self = [super initWithFrame:[self createRect]];
    return self;
}

- (CGRect)createRect{
    CGRect background= CGRectMake(_x, _y, _width, _height);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(context, background);
    return background;
}


@end

我想要做的就是在我的视图中添加一个Block类的实例:

#import "ViewController.h"
#import "Block.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    Block* b = [[Block alloc]initWithWidth:200 withHeight:200 withXPos:0 withYPos:200];
    [self.view addSubview:b];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

真的很困惑为什么这不起作用!

提前致谢。

1 个答案:

答案 0 :(得分:1)

你在哪里打createRect?这不是UIView方法,永远不会被自己调用。您的意思是使用drawRect:吗?

另外,您是否有理由制作自定义初始值设定项并且不仅仅覆盖initWithFrame:?你似乎以一种不必要的复杂方式完成了同样的事情。

编辑:我看到现在发生了什么。您在调用超级初始化程序时调用它。您是否尝试将其转换为drawRect:相反?现在,您正试图在视图甚至在屏幕上之前执行绘图。

这是一个应该可以正常工作的例子:

#import "Block.h"

@implementation Block

-(id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        // put any extra customization here, although your example doesn't require any
    }
    return self;
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);
    CGContextFillRect(context, rect);
}

@end