我已经通过编程创建了一个视图,并希望在该视图上添加2个按钮,但是在运行app视图时,它上的按钮不会出现。这里是我的示例代码,似乎问题在于框架,但如何根据框架调整按钮帧:
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];发布于 2014-12-23 07:14:23
首先,尝试这段代码,我只是删除了按钮式设置行。
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];https://stackoverflow.com/questions/27615635
复制相似问题