ios - iOS 标签首行宽度不同

标签 ios objective-c autolayout label width

我想将标签第一行的宽度设置为小于其余行。

如图所示 - 由于日期原因,它需要更短。 我该怎么做?

Label with different first line width

最佳答案

假设您的目标是 iOS7 或更高版本,您可以使用 TextKit 引入的非常方便的排除路径。

NSTextContainer(可通过UITextViewtextContainer 属性访问)提供了一个exclusionPaths。属性,您可以将其设置为一个或多个 UIBezierPath,代表文本应该环绕的区域。

因此,首先您需要确定您不想在其中看到任何文本的矩形(在您的情况下,我猜是时间标签 + 一些填充)。请注意,我们需要在 TextView 的坐标系中使用此矩形,因此您可能需要进行转换,例如:

CGRect timeLabelRect = [self.timeLabel convertRect:self.timeLabel.bounds toView:self.textView];
CGRect exclusionRect = CGRectInset(timeLabelRect, -10.f, -10.f); // add padding

一旦我们有了那个 rect,只需从它创建一个路径并将其设置为 TextView 文本容器上的(唯一)排除路径:

UIBezierPath *path = [UIBezierPath bezierPathWithRect:exclusionRect];
self.textView.textContainer.exclusionPaths = @[path];

就是这样!


Swift 中的完整示例(因为我从 Playground 复制/粘贴了它):

// just a plain container view
var container = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 400))

// the text view
var textView = UITextView(frame: CGRect(x: 0, y: 100, width: 300, height: 300))
textView.text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
container.addSubview(textView)

// a box (representing the time label in your case)
var blueBox = UIView(frame: CGRect(x: 250, y: 100, width: 50, height: 50))
blueBox.backgroundColor = .blueColor()
container.addSubview(blueBox)

此时它看起来像这样:

before exclusion path

现在,让我们简单地添加排除路径:

// configure exclusion path
let blueBoxRect = textView.convertRect(blueBox.bounds, fromView: blueBox)
let path = UIBezierPath(rect: blueBoxRect)
textView.textContainer.exclusionPaths = [path]

添加排除路径后是这样的:

after adding exclusion path

关于ios - iOS 标签首行宽度不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32049803/

相关文章:

ios - iOS/Swift 中的 UI 测试

iphone - ios:Ad Hoc应用程序安装到iPad,但没有安装到iPhone

ios - 在SwiftUI中隐藏表单的第一部分后的多余空间

ios - UIWebView 中的 Facebook 评论框高度不正确

autolayout - iOS 8 UIPageViewController 在转换后应用约束

ios - 自动布局父 View 高度变化

ios - 自动布局 ios 中 ScrollView subview 的动态高度

ios - 在 iOS 中为复杂图像着色

iphone - 转换前。 2010-09-11T00 :00:00+01:00 format to NSDate

objective-c - Objective-C++ block 语义