我有一个设置来在单击另一个按钮时创建UI按钮。一开始看起来一切都很简单,直到我决定创建自己的UI Button类。除了屏幕上没有显示按钮这一事实外,其中大部分都有效。我已经对可能导致它的原因有了一些想法,但让另一双眼睛看代码会很有帮助。
customButton.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.
}
view.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中没有使用的“返回自我”有关?
答案 0 :(得分:2)
是的,确实如此,由于class clusters,您应该真的将init
的返回值分配给实例:
customButton *newButton = [[customButton alloc] initWithFrame:f];
此外,传统上类名以大写字母开头。为您的班级CustomButton
命名。
修改:另一个问题是,在initWithFrame:
方法中,您不会在self
上设置属性,而是在另一个实例(button
)上设置属性。显然,这不会影响self
的状态。