UIButton 图片 + 文本 IOS

157

我需要一个带有图像和文本UIButton。 图像应该在顶部,文本应该在图像下方,两者都应该是可点击的。


希望这可以帮到你, 查看同时具有文本和图像的 UiButton http://stackoverflow.com/questions/4926581/uibutton-with-picture-and-text然后,您可以在视图上添加一个UITapGestureRecognizer来处理自定义按钮的点击。 - Humayun Ghani
请查看被接受的答案和此链接http://commandshift.co.uk/blog/2013/03/12/uibutton-edge-insets/,了解有关UIButton边缘的信息。 - onmyway133
12个回答

4
你需要为图片创建自定义的ImageView,为文本创建自定义的Label,然后将它们作为子视图添加到你的按钮上。就是这样。
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");

}

我想这对你会有帮助。

3

很简单,只需将图像添加为按钮的背景,并将文本添加到按钮的titlelabel中的uicontrolstatenormal状态即可。

[btn setBackgroundImage:[UIImage imageNamed:@"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:@"Click Me" forState:UIControlStateNormal];

4
图片下方的文本应该怎样排布? - holex
@holex: 非常感谢您的指导,我发现了其中的缺陷并做出相应的更改。 - Dhruv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接