首页 » 移动 » iOS中UILabel将部分文字改成上标的问题

iOS中UILabel将部分文字改成上标的问题

 

比如有一段文字如下:

iOS中[UILabel]将部分文字改成[上标]的问题。

需求是将中括号 [] 里面的内容改成上标,变成:

iOS中UILabel将部分文字改成上标的问题。

NSMutableAttributedString可以添加一个属性 NSBaselineOffsetAttributeName,将部分文字做偏移处理,这样也能实现效果,但是如果同时加上了NSFontAttributeName,那么这段文字在UILabel中只会显示一行,换行的部分会消失不见,没有找到具体的原因。

后来用了其它的属性kCTSuperscriptAttributeName替换,实现起来也更简单。

var superScripts = [String]()
if tempRemark.containsString("[") && tempRemark.containsString("]") {
    let array = tempRemark.componentsSeparatedByString("[")
    for temp in array {
        if temp.containsString("]") {
            let t = temp.componentsSeparatedByString("]")
            if t.count > 0 { superScripts.append("[\(t[0])]") }
        }
    }
}
let attrStr = NSMutableAttributedString(string: tempRemark, attributes: [NSFontAttributeName: UIFont(name: "ITCAvantGardeStd-Bk", size: 14)])
for s in superScripts {
    let totalLength = tempRemark.componentsSeparatedByString(s)[0].characters.count
    attrStr.addAttribute(NSFontAttributeName, value: UIFont(name: "ITCAvantGardeStd-Bk", size: 10), range: NSMakeRange(totalLength!, s.characters.count))
    attrStr.addAttribute(String(kCTSuperscriptAttributeName), value: 1, range: NSMakeRange(totalLength!, s.characters.count))
    let tmpStr = s.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")
    attrStr.replaceCharactersInRange(NSMakeRange(totalLength!, s.characters.count), withString: tmpStr)
}
let remarkLabel = UILabel()
remarkLabel.lineBreakMode = .ByWordWrapping
remarkLabel.numberOfLines = 0
remarkLabel.attributedText = attrStr
self.addSubview(remarkLabel)

原文链接:iOS中UILabel将部分文字改成上标的问题,转载请注明来源!