3

I wish to align title and image in UiButton in such a manner that the title appears on the left and the image to the extreme right. Please note that the button is stretched so as to fill the screen horizontally.

The button layout should look something like this:- [title .. ]

The title should have some left padding. The image should have some right padding.

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

However, though the title is left align, there is a lot of space on it's left. The image does not show up at all!

4

3 回答 3

5

Following Code will work

UIButton *sectionheader=[[UIButton alloc]initWithFrame:CGRectMake(0,0,320,44)];
[sectionheader setImageEdgeInsets:UIEdgeInsetsMake(0,6,0,0)];
sectionheader.userInteractionEnabled=NO;
[sectionheader setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];

// Now Create Label and addsubview to button

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

And suppoce you value is going to change always and you want to make it perfect than Make UIButton class and than add above code in that category class than just call following method to change value of that label

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

privew

于 2013-07-26T06:42:08.643 回答
3

我会选择替代方案
你可以做的是在一个视图中添加三个控件。让我们说ParentView

1) yourButton 
2) yourlable // don't use button title instead use this lable.
3) imageView

现在使ParentViewautosize 如下所示:

在此处输入图像描述

所以yourButton水平拉伸它会自动调整大小ParentView。从这里开始,您只想关心位置。

在after中设置yourlable为极左并将 autosize 属性设置为:parentViewyourButton

在此处输入图像描述 因此它将始终保持在最左侧ParentView

并将imageView位置设置为最右侧parentView并将 autosize 属性设置为:
在此处输入图像描述因此它将始终保持在最右侧ParentView
希望它会有所帮助。

于 2013-07-26T06:15:07.803 回答
0

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

于 2013-07-26T06:17:16.357 回答