Par*_*oft 56 iphone margin padding uibutton uikit
我有以下布局,我正在尝试向左和右添加填充..
控件是一些禁用的Uibutton.

我创建按钮的代码是这样的:
UIButton *buttonTime = [[UIButton alloc] initWithFrame:CGRectMake(90, 10, 50, 20)];
[buttonTime setBackgroundImage:[[UIImage imageNamed:@"bubble.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:13] forState:UIControlStateDisabled];
[buttonTime setTitle:@"27 feb, 2011 11:10 PM" forState:UIControlStateDisabled];
[buttonTime setTitleColor:[UIColor blackColor] forState:UIControlStateDisabled];
buttonTime.titleLabel.font=[UIFont fontWithName:@"Helvetica" size:8.0];
buttonTime.titleLabel.lineBreakMode= UILineBreakModeWordWrap;
[buttonTime setEnabled:FALSE];
[scrollView addSubview:buttonTime];
[buttonTime release];
Run Code Online (Sandbox Code Playgroud)
Ego*_*r T 87
托罗的答案是完美的.您还可以在storyboard或xib中的Size Inspector中设置插入值.

Aec*_*Liu 72
// Swift
var titleEdgeInsets: UIEdgeInsets!
// Objective-C
@property(nonatomic) UIEdgeInsets titleEdgeInsets;
Run Code Online (Sandbox Code Playgroud)
使用此属性可以调整按钮标题的有效绘图矩形并重新定位.您可以为四个插图(顶部,左侧,底部,右侧)中的每一个指定不同的值.正值会缩小或缩小,使其靠近按钮的中心.负值会扩展或偏离该边缘.使用UIEdgeInsetsMake函数为此属性构造值.默认值为UIEdgeInsetsZero.
接受答案的挑战是设置titleEdgeInsets限制,如Apple的文档中所述:
此属性仅用于在布局期间定位标题.>按钮不使用此属性来确定intrinsicContentSize和> sizeThatFits(_ :).
这意味着只有在明确调整按钮大小以适合标题标签和边距时,设置边距才有效.如果标题太长或边距太大,标题文本可能会被剪裁.对于在编译时知道其标题的按钮,这是可以的,但对于可变长度按钮标题,可能会出现问题.
容纳变量标题长度的另一种方法是将其保留titleEdgeInsets为默认值.设置按钮的标题后,添加明确的宽度和高度约束,以适应按钮的标题标签和附加边距.例如:
let margin: CGFloat = 10.0
let button = UIButton()
button.setTitle("My Button Title", for .normal)
button.widthAnchor.constraint(equalToConstant: button.titleLabel!.intrinsicContentSize.width + margin * 2.0).isActive = true
button.heightAnchor.constraint(equalToConstant: button.titleLabel!.intrinsicContentSize.height + margin * 2.0).isActive = true
Run Code Online (Sandbox Code Playgroud)
定位按钮而不添加更多高度或宽度约束,无论标题长度如何,它都将正确显示.
在 Swift 4 中,注意contentEdgeInsetsnot的使用titleEdgeInsets:
btn.contentEdgeInsets = UIEdgeInsetsMake(8, 8, 8, 8)
btn.titleLabel?.lineBreakMode = .byWordWrapping
Run Code Online (Sandbox Code Playgroud)
这将使按钮包裹其文本并保持一行,只要它有空间+在周围添加一些填充
如果使用 UIButton 子类不太烦人,则此选项也是可行的
class Button: UIButton {
override var intrinsicContentSize: CGSize {
get {
let baseSize = super.intrinsicContentSize
return CGSize(width: baseSize.width + titleEdgeInsets.left + titleEdgeInsets.right,
height: baseSize.height + titleEdgeInsets.top + titleEdgeInsets.bottom)
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后titleEdgeInsets根据需要使用
let button = Button()
... configure button
button.titleEdgeInsets = ...
Run Code Online (Sandbox Code Playgroud)
使用上述解决方案,如果按钮周围有边框,一些文本会被剪掉。例如,名为“Delete something”的按钮标签最终会显示“Dele...ing”。如果您遇到此问题,这是解决方案:
aButton.contentEdgeInsets = UIEdgeInset.init(top: 0, left: 8, bottom: 0, right: 8)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43192 次 |
| 最近记录: |