我是一个学习iOS的安卓开发人员。如何在iOS Swift中向UILabel添加填充(插入)?我还没有成功地找到一个关于这方面的简单教程。谢谢。
另外,如何向Swift中的UI元素添加边距?当我尝试下面的操作时,什么都没有更新(点击“添加约束”)。
发布于 2016-09-23 07:45:15
这是你需要在Swift 3中添加的代码:
class InsetLabel: UILabel {
let topInset = CGFloat(0)
let bottomInset = CGFloat(0)
let leftInset = CGFloat(20)
let rightInset = CGFloat(20)
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override public var intrinsicContentSize: CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
发布于 2016-01-25 06:33:33
需要添加以下内容:
class InsetLabel: UILabel {
let topInset = CGFloat(12.0), bottomInset = CGFloat(12.0), leftInset = CGFloat(12.0), rightInset = CGFloat(12.0)
override func drawTextInRect(rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func intrinsicContentSize() -> CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize()
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
}
发布于 2017-02-25 04:05:40
有一个简单的使用故事板的解决方案。在情节提要中,创建一个UIView对象,该对象的用途是围绕标签,以便为标签提供填充。然后,同样从故事板中,将您的UILabel放入该视图中。现在选择UILabel对象并通过单击"Pin“图标打开Add New Constraints弹出窗口。如果希望UILabel周围的填充始终为5,请在添加新约束弹出窗口中单击4个红色I形梁中的每一个,然后在I形梁旁边的4个框中键入5。如果您先键入5,然后单击I型梁,XCode将恢复为您键入5之前框中的任何值。最后单击Add Constraints按钮。
在添加约束弹出菜单中,XCode将忽略尚未单击相应红色工字梁的顶部、左侧、右侧或底部约束值。这可能回答了你问题的第二部分。
还要记住设置您添加的UIView的约束。如果你没有定义它在故事板中的位置(例如,固定在视图控制器的主视图的顶部和左侧),它将不会被分配一个默认位置,当你运行你的应用程序时,它可能根本不会显示。
https://stackoverflow.com/questions/32239457
复制相似问题