我已经以编程方式创建了一个视图,并希望在该视图上添加2个按钮,但在运行应用视图时,其上的按钮不会显示。这是我的示例代码,似乎问题是框架,但如何根据视图框架调整按钮框架:
cv = [[UIView alloc]initWithFrame:CGRectMake(200, 60, 100, 80)];
UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(100,90, 200, 30)];
label1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[label1 setTitle: @"Mark as unread" forState: UIControlStateNormal];
label1.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
[label1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
label1.backgroundColor=[UIColor blackColor];
[cv addSubview:label1];
UIButton *label2 = [[UIButton alloc]initWithFrame:CGRectMake(-50,20, 200, 30)];
[label2 setTitle: @"Mark as read" forState: UIControlStateNormal];
label2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
label2.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
[label2 addTarget:self action:@selector(nonbuttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cv addSubview:label2];
答案 0 :(得分:1)
首先尝试这段代码,我只是删除了buttontype设置行。
UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
//label1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *label2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 40, 100, 30)];
//label2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
原因:label1
根据第一行中的框架创建,在下一行中,label1
将重新分配给由此创建的新按钮实例buttonWithType
方法。因此,在已经设置框架的第一个实例中,它被覆盖了。
因此你的代码会变成这样:
cv = [[UIView alloc]initWithFrame:CGRectMake(200, 60, 100, 80)];
UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
[label1 setTitle: @"Mark as unread" forState: UIControlStateNormal];
label1.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
[label1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
label1.backgroundColor=[UIColor blackColor];
[cv addSubview:label1];
UIButton *label2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 40, 100, 30)];
[label2 setTitle: @"Mark as read" forState: UIControlStateNormal];
label2.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0];
[label2 addTarget:self action:@selector(nonbuttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cv addSubview:label2];