我想设置一个UILabel的左插图/边距,但找不到这样做的方法。标签有一个背景集,所以仅仅改变它的原点是行不通的。这将是理想的插入文本10px左右在左手边。
当前回答
如果你在ios6 +中使用自动布局,你可以通过在UILabel的子类中调整intrinsicContentSize来实现。
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.textAlignment = NSTextAlignmentRight;
}
return self;
}
- (CGSize)intrinsicContentSize
{
CGSize size = [super intrinsicContentSize];
return CGSizeMake(size.width + 10.0, size.height);
}
其他回答
设置标签的textAlignment属性为NSTextAlignmentRight并增加它的宽度。
你也可以用一个自定义框架初始化你的UILabel来解决这个问题。
CGRect initialFrame = CGRectMake(0, 0, 100, 100);
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 10, 0, 0);
CGRect paddedFrame = UIEdgeInsetsInsetRect(initialFrame, contentInsets);
self.label = [[UILabel alloc] initWithFrame:paddedFrame];
向CGRect Tricks致敬。
如果你不想使用一个额外的父视图来设置背景,你可以子类化UILabel并重写textRectForBounds: limitedtonumberolines:。我会添加一个textEdgeInsets属性或类似的,然后做
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,textEdgeInsets) limitedToNumberOfLines:numberOfLines];
}
为了健壮性,你可能还想在setTextEdgeInsets:中调用[self setNeedsDisplay],但我通常不这么做。
如果是单行,只需在左侧添加空格,超过一行的填充将再次为0。
[self.myLabel setText:[NSString stringWithFormat:@" %@", self.myShortString]];
Swift 4版的blyabtroi解决方案
let leadingMargin: CGFloat = 10
let trailingMargin: CGFloat = 10
let style = NSMutableParagraphStyle()
style.alignment = .justified
style.firstLineHeadIndent = leadingMargin
style.headIndent = leadingMargin
style.tailIndent = trailingMargin
label.attributedText = NSAttributedString(string: "Label with margins",
attributes: [NSAttributedStringKey.paragraphStyle: style])
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务