Ios 对齐UiButton中的图像和标题

Ios 对齐UiButton中的图像和标题,ios,ios5,Ios,Ios5,我希望在UiButton中对齐标题和图像,使标题显示在左侧,图像显示在最右侧。 请注意,按钮被拉伸,以便水平填充屏幕 按钮布局应如下所示:- [标题..] 标题应该有一些空白。 图像应该有一些正确的填充 CGFloat width = self.frame.size.width; CGFloat imageWidth = [button currentImage].size.width; button.contentHorizontalAlignment = UIControlContentHo

我希望在UiButton中对齐标题和图像,使标题显示在左侧,图像显示在最右侧。 请注意,按钮被拉伸,以便水平填充屏幕

按钮布局应如下所示:- [标题..]

标题应该有一些空白。 图像应该有一些正确的填充

CGFloat width = self.frame.size.width;
CGFloat imageWidth = [button currentImage].size.width;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; 
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, width - imageWidth - 10, 0, 0)];

然而,尽管标题是左对齐的,但它的左边有很多空间。图像根本不显示

我将选择alternative
您可以在一个视图中添加三个控件。比如说
ParentView

1) yourButton 
2) yourlable // don't use button title instead use this lable.
3) imageView
现在,使父视图自动调整大小,如下所示:

因此,当
按钮
水平拉伸时,它将自动调整
父视图的大小
。 从现在开始,你只需要注意位置

yourlable
设置为
parentView
yourButton
之后的最左边,并将autosize属性设置为:

因此,它将始终保持在父视图的最左边
并将
imageView
位置设置为
parentView
中的最右侧,并将autosize属性设置为:
因此,它将始终保持在父视图的最右边
希望对您有所帮助。

如果您在xib中添加了按钮,并且希望设置标题和图像,那么您可以从属性检查器进行设置。 在attributeinspector中有一个名为Edge的属性。默认情况下,它已设置内容。但是还有另外两个选项,分别命名为Title和Image。
在Inset属性的正下方,可以根据需要设置标题和图像。如果选择“标题”,则可以为图像设置标题(根据需要向左或向右移动)

以下代码也可以使用

UIButton *sectionheader=[[UIButton alloc]initWithFrame:CGRectMake(0,0,320,44)];
[sectionheader setImageEdgeInsets:UIEdgeInsetsMake(0,6,0,0)];
sectionheader.userInteractionEnabled=NO;
[sectionheader setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
//现在创建标签并将子视图添加到按钮

UILabel *lblkey=[[UILabel alloc] initWithFrame:CGRectMake(0,0,sectionheader.frame.size.width-10,sectionheader.frame.size.height)];

lblkey.accessibilityValue=@"Value";
lblkey.font=[UIFont fontWithName:themefont size:20];
lblkey.text=[creteria uppercaseString];
lblkey.backgroundColor=[UIColor clearColor];
lblkey.shadowColor = [UIColor blackColor];
lblkey.shadowOffset = CGSizeMake(0, 2);
lblkey.textAlignment=NSTextAlignmentRight;
lblkey.textColor=[UIColor whiteColor];
[sectionheader addSubview:lblkey];
而suppoce您的值将始终更改,并且您希望使其变得完美,而不是使
UIButton
类,并在该类别类中添加上述代码,而不仅仅是调用以下方法来更改该标签的值

+(void)settitle:(NSString *)value:(UIButton *)selfbutton
{
     for (UILabel *valuelabel in selfbutton.subviews)
     {
         if ([valuelabel.accessibilityValue isEqualToString:@"Value"])
         {
             valuelabel.text=value;
         }
     }   
}

请添加用于将图像添加到UIButton的代码[按钮设置图像:图像状态:UIControlStateNormal];您在xib中添加了按钮或自定义按钮?这只是一个uibutton。请查看下面的我的ans。更多详细答案和图片如下: