是否可能调整UIButton的titleLabel的x、y位置?

127

能否调整 UIButtontitleLabel 的 x,y 位置?

这是我的代码:

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [btn setFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
    [btn setTitle:[NSString stringWithFormat:@"Button %d", i+1] forState:UIControlStateNormal];     
    [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.frame = ???

这就是你所需要的:https://dev59.com/FnbZa4cB1Zd3GeqPCzLh - user3928882
5个回答

462
//make the buttons content appear in the top-left
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];

//move text 10 pixels down and right
[button setTitleEdgeInsets:UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 0.0f)];

并且在Swift中

//make the buttons content appear in the top-left
button.contentHorizontalAlignment = .Left
button.contentVerticalAlignment = .Top

//move text 10 pixels down and right
button.titleEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 0.0, 0.0)

Swift 5

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.titleEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 0.0, right: 0.0)

4
我甚至不需要前两行... setTitleEdgeInsets: 是我发现必要的来调整文本位置。 - ArtOfWarfare
这肯定是正确的,但可能更容易通过使用界面构建器来实现(如我的答案所述)。 - eladleb
前两行将您的文本定位到0,0(x,y)。这可以防止相对定位;特别是如果您在xib中设置了默认对齐方式。 - JBB
我从Web服务中分配按钮标题并为按钮分配背景图像。有时Web服务的值超过10个字母。在这种情况下,它会显示点线。如果Web服务的值增加,则需要增加按钮图像...如何做到? - Shalini
@ArtOfWarfare:如果您的按钮高度更大并且需要进行从左到右的对齐,则前两行将显示在图片中... 对于普通按钮,是的,它们是无用的... - Fahim Parkar

40
使用属性检查器(在编辑XIB/Storyboard时出现)是最简单的视觉方法,将“edge”属性设置为标题,调整其插图,然后将“edge”属性设置为图像,并相应地进行调整。
通常比编码更好,因为更易于维护,且高度可视化。 属性检查器设置

1
好的技巧是将 Edge 更改为 Title,然后调整插入! - netwire
1
作为以后的参考,自从Xcode 8以来,您可以在“尺寸检查器”中调整标题插图,而不是设置“edge”属性。 - dbmrq

14

从UIButton派生并实现以下方法:

- (CGRect)titleRectForContentRect:(CGRect)contentRect;

编辑:

@interface PositionTitleButton : UIButton
@property (nonatomic) CGPoint titleOrigin;
@end

@implementation PositionTextButton
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
  contentRect.origin = titleOrigin;
  return contentRect;
}
@end

谢谢,这正是我需要的。自动居中不够用。 - dmzza

4

我有一个扩展工具,用于我的项目:

extension UIButton {

    func moveTitle(horizontal hOffset: CGFloat, vertical vOffset: CGFloat) {
        self.titleEdgeInsets.left += hOffset
        self.titleEdgeInsets.top += vOffset
    }

}

0

这可以在xib中完成。选择您的按钮,转到“显示大小检查器”选项卡并设置插图。

enter image description here


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