Is it possible to adjust x,y position for titleLabel of UIButton?

∥☆過路亽.° 提交于 2019-12-03 01:32:59

问题


Is it possible to adjust the x,y position for the titleLabel of a UIButton?

Here is my code:

    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:


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

And in 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)



回答2:


The easiest way to do it visually is to use the attribute inspector** (appears when editing a xib/storyboard), setting the "edge" property to title, adjusting it's insets, then setting "edge" property to image, and adjusting accordingly. It's usually better than coding it , since it's easier to maintain and highly visual.




回答3:


Derive from UIButton and implement the following method:

- (CGRect)titleRectForContentRect:(CGRect)contentRect;

Edit:

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

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



回答4:


For my projects I've this extension utility:

extension UIButton {

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

}


来源:https://stackoverflow.com/questions/2808078/is-it-possible-to-adjust-x-y-position-for-titlelabel-of-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!