ios 是否有可能调整的x,y位置的UIButton的titleLabel?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2808078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:13:50  来源:igfitidea点击:

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

iosiphoneuibuttontextlabel

提问by RAGOpoR

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

是否有可能调整x,y坐标为titleLabelUIButton

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

回答by cannyboy

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

Swift 5

斯威夫特 5

button.contentHorizontalAlignment = .left
button.contentVerticalAlignment = .top
button.titleEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 0.0, right: 0.0)

回答by eladleb

The easiestway to do it visuallyis 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.

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

Attribute inspector setting

属性检查器设置

回答by drawnonward

Derive from UIButton and implement the following method:

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

- (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

回答by Luca Davanzo

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
    }

}