我需要一个带有图像和文本的UIButton
。 图像应该在顶部,文本应该在图像下方,两者都应该是可点击的。
我需要一个带有图像和文本的UIButton
。 图像应该在顶部,文本应该在图像下方,两者都应该是可点击的。
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.backgroundColor = [UIColor greenColor];
yourButton.frame = CGRectMake(140, 40, 175, 30);
[yourButton addTarget:self action:@selector(yourButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:yourButton];
UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, yourButton.frame.size.width, yourButton.frame.size.height/2)];
imageView1.image =[UIImage imageNamed:@"images.jpg"];
[yourButton addSubview:imageView1];
UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height/2)];
label.backgroundColor = [UIColor greenColor];
label.textAlignment= UITextAlignmentCenter;
label.text = @"ButtonTitle";
[yourButton addSubview:label];
为了测试目的,请使用yourButtonSelected:
方法
-(void)yourButtonSelected:(id)sender{
NSLog(@"Your Button Selected");
}
很简单,只需将图像添加为按钮的背景,并将文本添加到按钮的titlelabel中的uicontrolstatenormal状态即可。
[btn setBackgroundImage:[UIImage imageNamed:@"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:@"Click Me" forState:UIControlStateNormal];