127

是否可以调整 a 的 x,ytitleLabel位置UIButton

这是我的代码:

    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 = ???
4

5 回答 5

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

在斯威夫特

//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)

斯威夫特 5

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.titleEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 0.0, right: 0.0)
于 2010-05-21T17:20:11.077 回答
40

视觉上最简单的方法是使用属性检查器**(在编辑 xib/storyboard 时出现),将“ edge ”属性设置为标题,调整它的 insets,然后将“edge”属性设置为 image,并进行相应调整. 它通常比编码更好,因为它更易于维护且高度可视化。

属性检查器设置

于 2013-01-02T16:09:21.463 回答
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
于 2010-05-11T04:34:09.333 回答
4

对于我的项目,我有这个扩展实用程序:

extension UIButton {

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

}
于 2018-04-19T10:48:04.977 回答
0

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

在此处输入图像描述

于 2021-01-27T14:09:46.410 回答