在UIButton中添加图像作为附件

时间:2013-06-11 21:07:55

标签: ios objective-c cocoa-touch uibutton uiimage

我有以下UIButton我想在最右边添加一个Image。就像accessoryView

一样

我已经在使用backgroundImage了,我想避免将2张图像合并为1。

是否可以在UIButton中添加另一个AccesoryView图片,让我们说最右边有PLUS的图片? (我正在寻找一种在Button中插入新图像的方法)

enter image description here

@luisCien评论

我试过

    [_addImage setImage:[UIImage imageNamed:@"shareMe"] forState:UIControlStateNormal];
   _addImage.contentHorizontalAlignment =
        UIControlContentHorizontalAlignmentRight;

看起来像这样,我想将图像放在文本的右侧。 enter image description here

2 个答案:

答案 0 :(得分:13)

只需将其添加为子视图并选择您的坐标。尝试这样的事情:

UIImageView *yourPlusSign = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yourPlusSignImageTitle"]];
yourPlusSign.frame = CGRectMake(x, y, width, height);//choose values that fit properly inside the frame of your baseButton
//or grab the width and height of yourBaseButton and change accordingly
yourPlusSign.contentMode=UIViewContentModeScaleAspectFill;//or whichever mode works best for you
[yourBaseButton addSubview:yourPlusSign];

答案 1 :(得分:2)

您可以使用contentHorizontalAlignment的{​​{1}}属性并将其设置为UIButton,这会将您添加到其中的图片定位到最右侧。

编辑: 正如@danypata所建议的那样,你也可以使用UIButton的属性UIControlContentHorizontalAlignmentRight离开 您的'accessoryView'周围有一些边距,如下所示:

imageEdgeInsets

关于左边的文字和右边的图像,我相信这是不可能的(有人请你纠正我)。为此,我可以通过扩展[_addImage setImageEdgeInsets:UIEdgeInsetsMake(5, 0, 5, 10)]; 或添加UIControl来创建我自己的自定义按钮并设置它的框架(而不是使用UILabel的{​​{1}})并添加它作为按钮的子视图。

希望这有帮助!