gpt4 book ai didi

ios - 用 2 行截断 UILabel 的头部

转载 作者:行者123 更新时间:2023-11-28 06:29:39 24 4
gpt4 key购买 nike

我有一个 UIlabel,其 numberOfLines 为 2和 lineBreakMode = 截断头部

但是当我运行它时而不是像

这样在第一行截断头部
    ...1st Line Content
2nd Line Content

它像这样截断

    1st Line Content 
...2nd Line Content

我如何在第一行中截断标签的头部?

最佳答案

试试这段在 Swift 3 中测试过的代码

   let text = "Hello World! Hello World! Hello World! Hello World! "
let attString = NSMutableAttributedString(string: text)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
paragraphStyle.firstLineHeadIndent = 0
paragraphStyle.headIndent = 40 // set any vallue
paragraphStyle.lineBreakMode = .byTruncatingHead
attString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attString.length))
attString.addAttribute(NSFontAttributeName, value: UIFont(name: "Arial", size: 25)!, range: NSMakeRange(0, attString.length))
label.attributedText = attString // label is your UILabel
label.numberOfLines = 2

输出 1:

enter image description here

    paragraphStyle.firstLineHeadIndent = 40 // set any vallue
paragraphStyle.headIndent = 0

输出 2:

enter image description here

更新:您可以通过组合两个属性字符串来实现

    let dotAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont(name: "Arial", size: 25)]
let textAttributes = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont(name: "Arial", size: 25)]

let dotString = NSMutableAttributedString(string: ". . . ", attributes: dotAttributes)
let textString = NSMutableAttributedString(string: "Hello World! Hello World! Hello World! Hello World!", attributes: textAttributes)

let totalString = NSMutableAttributedString()
totalString.append(dotString)
totalString.append(textString)

label.numberOfLines = 2
label.attributedText = totalString

注意:您可以使用 paragraphStyle(headIndent) 创建左边距。

    let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
paragraphStyle.firstLineHeadIndent = 5
paragraphStyle.headIndent = 5 // set any vallue
paragraphStyle.lineBreakMode = .byTruncatingHead
totalString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, totalString.length))

输出:

enter image description here

关于ios - 用 2 行截断 UILabel 的头部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40716727/

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