代码之家  ›  专栏  ›  技术社区  ›  Joseph Astrahan

中心3不均匀标签-界面生成器

  •  0
  • Joseph Astrahan  · 技术社区  · 5 年前

    enter image description here

    如何在视图中水平居中放置3个不同大小的标签(数字的数据也将是动态的)?

    我尝试过的事情:

    0 回复  |  直到 5 年前
        1
  •  1
  •   matt    5 年前

    我会这样做的。我会做这个的 标签,毕竟很容易居中。好吧,我想你知道怎么做。

    然后我将使用一个属性化字符串来创建字符串的不同部分,包括“subscripting”。因此,首先我要扩展属性化的字符串键,以包括三个部分:

    extension NSAttributedString.Key {
        static let part1 = NSAttributedString.Key(rawValue: "part1")
        static let part2 = NSAttributedString.Key(rawValue: "part2")
        static let part3 = NSAttributedString.Key(rawValue: "part3")
    }
    

    let mas = NSMutableAttributedString()
    mas.append(NSAttributedString(string: "Late BED = ", attributes: [
        .font:UIFont.systemFont(ofSize: 15),
        .foregroundColor:UIColor.black,
        .part1:"part1"
    ]))
    mas.append(NSAttributedString(string: "20.0", attributes: [
        .font:UIFont.systemFont(ofSize: 15),
        .foregroundColor:UIColor.black,
        .part2:"part2"
    ]))
    mas.append(NSAttributedString(string: " Gy(3.0)", attributes: [
        .font:UIFont.systemFont(ofSize: 9),
        .foregroundColor:UIColor.black,
        .baselineOffset:-10,
        .part3:"part3"
    ]))
    self.label.attributedText = mas
    

    结果看起来像你得到的,当然你可以根据需要调整它:

    enter image description here

    例如,假设我想将“20.0”更改为“30.4”。这是你的第二个标签,也是我的 .part2 . 以下是您的操作方法:

    let s = self.label.attributedText
    // skip past part 1 and find part 2
    var r = NSRange()
    let mas = s?.mutableCopy() as! NSMutableAttributedString
    let _ = mas.attribute(.part2, at: 0, longestEffectiveRange: &r, 
        in: NSRange(location: 0, length: 100))
    // find range of part 2
    let _ = mas.attribute(.part2, at: r.length, longestEffectiveRange: &r, 
        in: NSRange(location: 0, length: 100))
    mas.replaceCharacters(in: r, with: "30.4")
    self.label.attributedText = mas