gpt4 book ai didi

ios - iOS 标签首行宽度不同

转载 作者:行者123 更新时间:2023-11-28 19:46:07 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com