是否可以调整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 = ??? 
 //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) 

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

属性检查器设置

从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 
Interesting Posts