0

当单击另一个按钮时,我有一个设置来创建一个 UI 按钮。起初一切似乎都很简单,直到我决定创建自己的 UI Button 类。大部分都有效,除了按钮没有显示在屏幕上。我已经对可能导致它的原因有了一些想法,但是让另一双眼睛查看代码会很有帮助。

自定义按钮.m

- (id)initWithFrame:(CGRect)frame   //this function was provided
{
    self = [super initWithFrame:frame];
    if (self) {
        //this is stuff I wrote, that could be wrong.
        UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(1,2,100,50);
        [button setTitle:@"Test!" forState:UIControlStateNormal];
        }
   return self;
    NSLog(@"worked?"); //this log is actually outputted! However, if I put this before "return self", it doesn't work. So I'm guessing the problem is with "return self" not being caught.


}

视图.m

-(IBAction)createDrawer:(id)sender {
    customButton* newButton = [customButton alloc]; 
    [newButton initWithFrame:newButton.frame]; 
    [self.containerView addSubview:newButton];
    NSLog(@"asdasdadads"); //this actually gets executed, when button is clicked
    }

view.m 的第 3 行给出警告“未使用表达式结果”。我猜这与initWithFrame没有使用“返回自我”有关吗?

4

1 回答 1

2

是的,确实如此,并且由于类 clusters,您实际上应该将返回值分配给init实例:

customButton *newButton = [[customButton alloc] initWithFrame:f];

此外,通常类名以大写字母开头。命名你的班级CustomButton

编辑:另一个问题是,在该initWithFrame:方法中,您没有self在另一个实例(button)上设置属性。显然,这不会影响self.

于 2013-05-21T04:48:38.657 回答