我想设置一个UILabel的左插图/边距,但找不到这样做的方法。标签有一个背景集,所以仅仅改变它的原点是行不通的。这将是理想的插入文本10px左右在左手边。
当前回答
设置标签的textAlignment属性为NSTextAlignmentRight并增加它的宽度。
其他回答
我认为UILabel类没有设置边距的方法。为什么不把标签的位置设置在需要的位置?
见下面的代码:
UILabel *label = [[UILabel alloc] init];
label.text = @"This is label";
label.frame = CGRectMake(0,0,100,100);
如果来自接口构建器,则按以下方式定位Label:
yourLabel.frame = CGRectMake(0,0,100,100);
设置标签的textAlignment属性为NSTextAlignmentRight并增加它的宽度。
Swift 3 &自动布局兼容版本:
class InsetLabel: UILabel {
var insets = UIEdgeInsets()
convenience init(insets: UIEdgeInsets) {
self.init(frame: CGRect.zero)
self.insets = insets
}
convenience init(dx: CGFloat, dy: CGFloat) {
let insets = UIEdgeInsets(top: dy, left: dx, bottom: dy, right: dx)
self.init(insets: insets)
}
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += insets.left + insets.right
size.height += insets.top + insets.bottom
return size
}
}
很多答案都很复杂。在某些情况下,这是必要的。然而,如果你正在阅读这篇文章,你的标签没有左右边距,你只是想要一点填充,这里是整个解决方案:
第一步:在结尾添加空格(按几次空格键)
步骤2:设置标签的文本对齐方式为居中
Done
对于Xamarin用户(使用统一API):
class UIMarginLabel : UILabel
{
public UIMarginLabel()
{
}
public UIMarginLabel( CGRect frame ) : base( frame )
{
}
public UIEdgeInsets Insets { get; set; }
public override void DrawText( CGRect rect )
{
base.DrawText( Insets.InsetRect( rect ) );
}
}
对于那些使用原始MonoTouch API的人:
public class UIMarginLabel : UILabel
{
public UIEdgeInsets Insets { get; set; }
public UIMarginLabel() : base()
{
Insets = new UIEdgeInsets(0, 0, 0, 0);
}
public UIMarginLabel(RectangleF frame) : base(frame)
{
Insets = new UIEdgeInsets(0, 0, 0, 0);
}
public override void DrawText(RectangleF frame)
{
base.DrawText(new RectangleF(
frame.X + Insets.Left,
frame.Y + Insets.Top,
frame.Width - Insets.Left - Insets.Right,
frame.Height - Insets.Top - Insets.Bottom));
}
}
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务