【问题标题】:UIButton text and imageUIButton 文本和图像
【发布时间】:2015-04-11 11:31:41
【问题描述】:

我有一个 UIButton。在那个 UIButton 中,我必须显示文本和图像。图像应显示在文本之后。基于文本我想调整按钮框架。 看图片。在文本“我是按钮”之后,我想添加一个像箭头这样的图像。

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];

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

【问题讨论】:

  • 尝试玩转 UIButton 的 imageEdgeInsetstitleEdgeInsets 属性。你一定会得到你需要的。

标签: ios objective-c xcode uiimageview uibutton


【解决方案1】:

您不必在UIButton 上添加UIImageView 即可获得此行为。 UIButton 本身有一些属性。将橙色图像设置为buttonbackground image,将箭头图像设置为buttonimage。然后调整titleinsetsbuttonimage,将标题向左移动,箭头图像向右移动。

    [btn setBackgroundImage:[UIImage imageNamed:@"orange_bg"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"arrow"] forState:UIControlStateNormal];

[btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -60, 0)];
[btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 125, 0)];

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

【讨论】:

  • 感谢@Suresh,我的文字会不断变化。根据文字我想调整图像。
  • 然后你必须使用 sizeWithFont 找到文本的大小并动态调整插图。
  • 以上代码不工作。如果显示图像,则不会显示文本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 2011-06-01
  • 1970-01-01
  • 2014-09-02
  • 2015-05-27
相关资源
最近更新 更多