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

问题描述:

这里是我的代码是否可以调整UIButton的位置x,y titleLabel?

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 = ??? 
+1

请选择其他答案,以便我们删除非常负面的答案。否则解释你为什么这样做。 – tchrist 2012-09-09 03:46:17

+1

为什么不接受该答案? – 2013-11-07 12:27:31

+0

这就是你需要的一切http://stackoverflow.com/questions/18484747/uibutton-titleedgeinsets – 2015-10-06 11:09:59

派生从的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 
+0

你能告诉我一些例子吗? – RAGOpoR 2010-05-11 05:27:11

+0

谢谢,这是我真正需要的。自动居中是不够的。 – dmzza 2014-09-27 01:54:30

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

这绝对是最好的答案 – greenisus 2011-04-12 16:10:56

+3

我想知道为什么提问者选择了其他答案。这个更好。 – Joshua 2011-06-29 18:11:26

+4

我甚至不需要前两行......'setTitleEdgeInsets:'是我发现的所有必要的文本。 – ArtOfWarfare 2013-01-01 18:34:32

最简单的办法做到这一点视觉是使用属性检查器**,设置“边缘”财产所有权,调整它的插图,然后(在编辑时,厦门国际银行/故事板出现)将“边缘”属性设置为图像,并相应地进行调整。 它通常比编码更好,因为它更容易维护并且具有高度的视觉效果。

Attribute inspector setting

+1

好提示将'Edge'改为'Title',然后调整插入! – Dean 2015-04-30 16:02:19