如何在iPhone应用程序中实现UIButton/UILabel'填充'

60 iphone padding uibutton uiview uilabel

我的iPhone应用程序中有各种视图需要填充,例如左边是文本对齐的自定义UIButton,背景颜色为UILabel.

这可能是一个非常愚蠢的问题,但我如何应用'填充'来移动左边的文本?

我已经厌倦了使用边界等没有任何成功.

我知道我可以UILabel用背景颜色为我创建一个包装器视图,但它看起来有点矫枉过正.

非常感谢.

Raf*_*fAl 98

我正在使用自动布局.为我工作溶液设置UIButtoncontentEdgeInsets.

ObjC

button.contentEdgeInsets = UIEdgeInsetsMake(0.0f, 30.0f, 0.0f, 30.0f);
Run Code Online (Sandbox Code Playgroud)

迅速

button.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 30.0, bottom: 0.0, right: 30.0)
Run Code Online (Sandbox Code Playgroud)

  • 请未来的读者注意,iOS 15 似乎已弃用“contentEdgeInsets”。现在,在使用 [UIButtonConfiguration](https://developer.apple.com/documentation/uikit/uibutton/configuration) 时,该属性将被忽略。其相关方法 [.setDefaultContentInsets](https://developer.apple.com/documentation/uikit/uibutton/configuration/3869632-setdefaultcontentinsets?changes=_4) 正在显示“Beta Software”通知。 (2认同)

小智 22

好的,到目前为止我找到的最简单的解决方案是:

self.textAlignment = UITextAlignmentCenter; 
[self sizeToFit]; 
CGRect frame = self.frame;
frame.size.width += 20; //l + r padding 
self.frame = frame;
Run Code Online (Sandbox Code Playgroud)

不完全是我想要的,但它确实有效.


Gir*_*hai 17

要在uibutton文本中设置填充,您需要使用UIButton的UIButton属性.在Storyboard中,要设置内容插入,请执行以下步骤: -

  1. 选择View controller,选择uibutton
  2. 转到Utilities面板(Command + Option + 0)并选择Attributes Inspector(Command + Option + 4)
  3. 现在选择内容边缘并设置插图按您的要求.(见截图)

在此输入图像描述

  • 现在它是Size Inspector下的Button - > Content Insets (6认同)
  • 现在它在尺寸检查器中 (4认同)
  • XCode 9以上的UIButton->大小检查器->`Content Insets` ==>如下图所示:/sf/answers/3497149701/ (2认同)

Bro*_*son 7

要向UILabel添加填充,最灵活的方法是子类化UILabel并添加edgeInsets属性.然后,您可以设置所需的插图,并相应地绘制标签.

OSLabel.h

#import <UIKit/UIKit.h>

@interface OSLabel : UILabel

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end
Run Code Online (Sandbox Code Playgroud)

OSLabel.m

#import "OSLabel.h"

@implementation OSLabel

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if(self){
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}

@end
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 5

Xcode 9 上,插图现在位于Size Inspector而不是 Attributes Inspector 中:

Xcode 9 尺寸检查器 - 按钮插入