ios - 如何根据 UILabel 行宽设置 UIImageView 的宽度

标签 ios swift uiimageview uilabel

我最近开始在 Xcode 中使用 Swift 开发一个应用程序,并尝试创建一个文本气泡。为此,我需要获取多行 UILabel 中最长文本行的宽度。例如,如果我有这段文字(我会在一定长度后自动设置换行符):

Hello there, this is 
an example piece of text

我想返回第二行文本的宽度。我已经尝试使用 sizeToFit() 来大大简化我的工作,但是由于我的其他代码,这不是一个选项,因为它会导致其他问题(我的代码在下面)。是否有一种不使用 sizeToFit() 的纯编程方式来获取此值?任何帮助将非常感激。我的代码:

bubbleContents.text = textMessage
bubbleContents.numberOfLines = 0
bubbleContents.lineBreakMode = .byWordWrapping

bubbleContents.bounds.size.width = 2000
var widthText = bubbleContents.intrinsicContentSize.width
bubbleContents.bounds.size.width = 266
print(textMessage)
print(widthText)
if widthText > 266 {
    let numRows = Int(widthText/266)
    print(numRows)
    //bubbleContents.frame.origin.y += CGFloat((Double(numRows)*10.25))
    var currentHeight = 44.0
    currentHeight += Double((Double(numRows)*20.5))
    bubbleContents.bounds.size.height = CGFloat(currentHeight)
    heightOfCell = Double(currentHeight)
    let originalTransform = self.bubbleContents.transform
    let scaledTransform = originalTransform
    let scaledAndTranslatedTransform = scaledTransform.translatedBy(x: 0, y: CGFloat(Double(numRows)*20.5))
    //self.bubbleContents.transform = scaledAndTranslatedTransform
}
else {
    heightOfCell = 44.0
}

bubble.frame = CGRect(x: 0, y: 0, width: Double(widthText + 30), height: heightOfCell - 4)
bubbleContents.center.y = bubble.center.y

这是我当前文本气泡的图像:

Image

最佳答案

您可以使用 NSAttributedString,boundingRect(with:options:context:)方法,首先创建 NSAttributedString具有诸如 UILabel 字体等属性

let attributes: [NSAttributedString.Key : Any] = [.font: bubbleContents.font]
let atStr = NSAttributedString(string: textMessage, attributes: attributes)

现在使用 atStr.boundingRect(with:options:context:)方法,像这样:

let bounds = CGSize(width: 266.0, height: .greatestFiniteMagnitude)
let bubbleSize = atStr.boundingRect(with: bounds, options: [.usesLineFragmentOrigin, .usesFontLeading, .usesDeviceMetrics], context: nil).size

用法:

bubble.frame.size.width = bubbleSize.width
bubble.frame.size.height = max(bubbleSize.height, 44.0)

关于ios - 如何根据 UILabel 行宽设置 UIImageView 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55669685/

相关文章:

ios - 将 iPhone 应用程序上传到 AppStore 的步骤

ios - 如何使按钮变灰以让用户知道它当前在 iOS 中被禁用?

ios - 选项卡栏图标除第一个图标外均已加载。在模拟器中工作。 Objective-c

ios - 从 WKWebView 调用时无法使用 JavaScript 在移动 Safari 中打开链接

html - 使用字体从 HTML 设置标签文本 NSAttributedString

ios - 当我导航到包含 ARSCNView 的 View Controller 时,会出现空白屏幕

ios - 无法添加 UIImageView Xcode Swift

ios - UITableView 不读取数组

ios - 在 xcode 中将 favicon.ico 转换为 png

iphone - UIButton 的图像丢失了新设置的图像