在UiButton中对齐图像和标题

3
我希望您能够将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)];

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


[button setImage:image forState:UIControlStateNormal]; 将图像设置为按钮的正常状态。 - Ankit Agarwal
这只是一个UIButton。 - Ankit Agarwal
请查看下面我的答案 - Mital
[UIView] > [UILabel + UIImageView] + UITapGestureRecognizer 这个怎么样? - TheTiger
我在这里添加了一个答案[https://dev59.com/gXE85IYBdhLWcg3wdDSz],解释了如何使用Interface Builder对图像和文本进行对齐。 - n8tr
显示剩余4条评论
3个回答

5
以下代码可以正常工作。
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];

假设您的值将不断变化,并且您希望使其完美,那么请创建一个 UIButton 类,然后将上述代码添加到该类别中,然后只需调用以下方法即可更改该标签的值。
+(void)settitle:(NSString *)value:(UIButton *)selfbutton
{
     for (UILabel *valuelabel in selfbutton.subviews)
     {
         if ([valuelabel.accessibilityValue isEqualToString:@"Value"])
         {
             valuelabel.text=value;
         }
     }   
}

privew


3

我将使用替代方案
您可以在一个视图中添加三个控件,比如ParentView

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

现在让ParentView自动调整大小,如下所示:

enter image description here

因此,当yourButton水平拉伸时,它将自动调整ParentView的大小。从这里开始,您只需要关注位置。
yourButton后将yourlable设置为位于parentView的极左端,并将自动大小属性设置为:

enter image description here 这样它将始终保持在ParentView的极左端

并将imageView位置设置为在parentView的极右端,并将自动大小属性设置为:
enter image description here 这样它将始终保持在ParentView的极右端
希望这可以帮到你。


0

如果您在XIB中添加了按钮并希望设置标题和图像,则可以从属性检查器中进行设置。 在属性检查器中有一个名为“边缘”的属性。默认情况下,它已经设置成内容。但是还有另外两个选项名称为Title和Image。 并且正好在Inset Property的下方,您可以按照您想要的方式设置标题和图像。如果选择标题,则可以设置标题(向左或向右移动),同样也适用于图像。


更详细的答案和图片请参考此链接:https://dev59.com/Xmgt5IYBdhLWcg3w7BoE - Andrei Konstantinov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接