2013-07-26 67 views
3

我希望在UiButton中对齐标题和图像,使标题出现在左侧,图像出现在最右侧。 请注意,按钮被拉伸以便水平填充屏幕。在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)]; 

不过,虽然标题是左对齐,有一个空间很多在它的左边。图像完全不显示!

+0

请添加使用的图像添加到UIButton的 – Stavash

+0

代码[按钮setImage:图像forState:UIControlStateNormal]。 –

+0

您在xib或自定义按钮中添加了按钮? – Mital

回答

3

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

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

现在让ParentView自动调整大小象下面这样:

enter image description here

从而yourButton将水平拉伸它会自动调整ParentView。 从这里开始,你只是想要关心职位。

设置yourlable极左在parentViewyourButton后,并设置自动调整属性:

enter image description here 所以它会一直保持到ParentView

极左并设置parentViewimageView位置极右并设置自动调整大小财产到:
enter image description here所以它将永远保持到极端的权利ParentView
希望它会有所帮助。

0

如果你已经在xib中添加了按钮,并且你想设置标题和图像,那么你可以从属性检查器来完成。在attributeinspector中有一个名为Edge的属性。默认情况下它已经设置了内容。但还有其他两个选项命名为标题和图像。 ,正好在Inset Property下方,您可以根据需要设置标题和图像。如果您选择标题,那么你可以设置标题(向左或向右移动为u想要的)同样的图像也

+0

更详细的答案与图像在这里:http://stackoverflow.com/questions/11717219/uibutton-image-text-ios –

5

下面的代码将工作

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

//现在创建标签和addsubview到按钮

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

[email protected]"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]; 

并支持你的价值将永远改变,你想使它完美比制造UIButton类,并在该类别类中添加上述代码,而不是只调用以下方法来更改该标签的值

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

privew