ios - Swift:给定 UILabel 的宽度拆分字符串

标签 ios swift uitextview

如何根据 UILabel 的宽度拆分字符串。

str = "Here is a sample of a long string that wraps at the end of the screen three times." 

width = UIScreen.Main.Bounds.Width

预期结果

strArray = ["Here is a sample of a long", "string that wraps at the  end", "of the screen three times."]

看图:

enter image description here

目标是将行提取为字符串,而不是换行。

最佳答案

try below function

func getStringArrayFromLabel(in label: UILabel) -> [String] {

    /// An empty string's array
    var arrLines = [String]()

    guard let text = label.text, let font = label.font else {return arrLines}

    let rect = label.frame

    let myFont: CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil)
    let attStr = NSMutableAttributedString(string: text)
    attStr.addAttribute(kCTFontAttributeName as NSAttributedString.Key, value: myFont, range: NSRange(location: 0, length: attStr.length))

    let frameSetter: CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString)
    let path: CGMutablePath = CGMutablePath()
    path.addRect(CGRect(x: 0, y: 0, width: rect.size.width, height: 100000), transform: .identity)

    let frame: CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
    guard let lines = CTFrameGetLines(frame) as? [Any] else {return arrLines}

    for line in lines {
        let lineRef = line as! CTLine
        let lineRange: CFRange = CTLineGetStringRange(lineRef)
        let range = NSRange(location: lineRange.location, length: lineRange.length)
        let lineString: String = (text as NSString).substring(with: range)
        arrLines.append(lineString)
    }
    return arrLines
}

关于ios - Swift:给定 UILabel 的宽度拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57320095/

相关文章:

objective-c - 如何在 UICollectionView 委托(delegate)方法之前触发带完成的 NSURLSession?

ios - UIPanGestureRecognizer 在 iPhone 5s + iOS 7 上不准确

c++ - 使用OpenCV从2D图像点计算3D世界点

objective-c - 为什么这个 UIButton/IBAction 不刷新我的页面?

ios - Swift UITableView 委托(delegate)和数据源声明和保留周期

ios - 使用 CGAffineTransform 和 PanGestureRecognizer 旋转 ImageView

ios - 禁止在iOS 9上打开3D触摸屏?

iphone - 转到 UITextView 中的特定行

ios - 模仿 UITextView 的默认双击行为

ios - Cordova 平台添加 ios - 错误命令失败,退出代码为 2