可变字符串颜色更改会将字符显示为方形

时间:2016-11-13 01:07:42

标签: ios swift3

我正在更改表格视图部分标题的最后一个字符的颜色,并且得到了iOS 9+,swift 3的奇怪结果。

最后一个字符是复选标记✔︎,颜色为绿色。结果是绿色方块而不是绿色复选标记。如果我打印到控制台,则勾选标记会正确显示。如果我删除了颜色变化,它会显示复选标记(黑色)。如果我使用另一个符号,例如双感叹号,它可以正常工作。

简化代码

struct PersonConstants{
    static let DEFAULT_STATUS_INDEX : Int = 1
    static let validStatus : NSArray = ["✔︎","?","‼"]
}

let colorsArray = [
    UIColor(red: 29/255.0, green:166/255.0, blue:47/255.0, alpha:1.0),
    UIColor(red: 0/255.0, green: 0/255.0, blue: 255/255.0, alpha: 1.0),
    UIColor(red: 225/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0),
]
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
    var title = String(Safe.count) + " "
    title += NSLocalizedString("Accounted", comment: "")
    title += ": " + String(PersonConstants.validStatus[0] as! NSString)
    return title
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let view = view as? UITableViewHeaderFooterView {
        view.textLabel!.textColor = UIColor.black
        view.textLabel!.font = UIFont.italicSystemFont(ofSize: 17.0)

        myMutableString = NSMutableAttributedString(string: view.textLabel!.text! as String)

        if sectionTwo.count > 0{
            myMutableString.addAttribute(NSForegroundColorAttributeName, value: colorsArray[0], range: NSRange(location: (view.textLabel!.text!).characters.count-1,length:1))
            view.textLabel!.attributedText = myMutableString
            //print(myMutableString.string)
        }else{
            view.textLabel!.text = ""
        }
    }
}

结果不好

enter image description here

1 个答案:

答案 0 :(得分:1)

这是因为NSMutableAttributedString适用于基于UTF-16的偏移量和计数,您需要为NSRange的属性传递基于UTF-16的NSMutableAttributedString

在Swift 3中这不是一项简单的任务......

let text = view.textLabel!.text ?? ""
let lastCharIndex = text.index(before: text.endIndex)
let lastCharUTF16Index = lastCharIndex.samePosition(in: text.utf16)
let location = text.utf16.startIndex.distance(to: lastCharUTF16Index)
let length = lastCharUTF16Index.distance(to: text.utf16.endIndex)
myMutableString.addAttribute(NSForegroundColorAttributeName, value: colorsArray[0],
                             range: NSRange(location: location, length: length))

顺便说一下,如果您将validStatus声明为:

static let validStatus: [String] = ["✔︎","?","‼"]

您可以使代码的其他部分更简单:

title += ": " + PersonConstants.validStatus[0]