簡體   English   中英

iOS自定義UIButton未出現在視圖中

[英]iOS Custom UIButton not appearing on view

我在重寫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

真的很困惑為什么這行不通!

提前致謝。

您在哪里調用createRect 那不是UIView方法,永遠不會被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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM