是否可以调整UIButton的位置x,y titleLabel?

RAG*_*poR 115 iphone uibutton textlabel ios

这是我的代码

    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 = ???
Run Code Online (Sandbox Code Playgroud)

can*_*boy 438

//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)];
Run Code Online (Sandbox Code Playgroud)

在斯威夫特

//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)
Run Code Online (Sandbox Code Playgroud)

  • 我甚至不需要前两行...`setTitleEdgeInsets:`是我发现移动文本所需的全部内容. (4认同)
  • 这绝对是最好的答案 (3认同)
  • 我想知道为什么提问者选择了另一个答案.这个更好. (3认同)

ela*_*leb 40

最简单的做方式在视觉上是使用属性检查员**,"设定(当编辑一个XIB /故事板时出现)边缘 "属性标题,调整它的插图,然后"边缘"属性设置为图像,并相应地调节.它通常比编码更好,因为它更容易维护和高度可视化.

属性检查器设置


dra*_*ard 14

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

- (CGRect)titleRectForContentRect:(CGRect)contentRect;
Run Code Online (Sandbox Code Playgroud)

编辑:

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

@implementation PositionTextButton
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
  contentRect.origin = titleOrigin;
  return contentRect;
}
@end
Run Code Online (Sandbox Code Playgroud)