UIButton文本和图像

时间:2015-02-11 07:14:14

标签: ios objective-c xcode uiimageview uibutton

我有一个UIButton。在UIButton我必须显示文字和图像。图像应在文本后显示。基于文本我想调整按钮框架。 Button With Text n Image 看图像。在文本"我是一个Button"之后,我想添加一个像箭头一样的图像。

UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
NSString *name = @"I am a button";
titleButton.titleLabel.text = [NSString stringWithFormat:@"%@", name];
titleButton.titleLabel.textColor = [UIColor whiteColor];
CGSize stringSize = [name sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"MyriadPro-Cond" size:24]}];
CGRect frame = CGRectMake(300, 30, stringSize.width, 30);
//frame.size.width = stringSize.width;
[titleButton setFrame:frame];
UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home.png"]];
image.frame = CGRectMake(stringSize.width, 14, 20, 13);
titleButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, stringSize.width+20, 0);
[titleButton addSubview:image];

我写了这样的代码。但它没有用。任何人都可以使它正确。提前致谢

1 个答案:

答案 0 :(得分:0)

您无需在UIImageView上添加UIButton即可获得此行为。 UIButton本身有一些属性。将橙色图像设置为background image的{​​{1}},将箭头图像设置为button的{​​{1}}。然后调整image的{​​{1}}和button的{​​{1}},将标题移到左侧,将箭头图像移到右侧。

insets

您必须根据图像和按钮大小调整插图。