直接使用代理方法attributedTitleForRow即可实现,不需要使用 func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView 方法
// MARK: - UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
switch component {
case 0: // 年
let str = "\(_defaultOriginYear + row)年"
return self.attributedStr(from: str)
case 1: // 月
let str = "\(1 + row)月"
return self.attributedStr(from: str)
case 2: // 日
let str = "\(1 + row)日"
return self.attributedStr(from: str)
case 3: // 时
let str = "\(row)时"
return self.attributedStr(from: str)
case 4: // 分
let str = "\(row)分"
return self.attributedStr(from: str)
default:
return nil
}
}
富文本文字方法如下:
private func attributedStr(from str: String)-> NSAttributedString {
// let attriStr = NSMutableAttributedString.init(string: str)
// let attri = [NSAttributedString.Key.foregroundColor: UIColor.darkGray33, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
// let range = NSRange.init(location: 0, length: str.count)
// attriStr.addAttributes(attri, range: range)
let attrTotal = NSMutableAttributedString(string: str)
let range = (str as NSString).range(of: str)
attrTotal.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.darkGray33, range: range)
attrTotal.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 14), range: range)
return attrTotal
}
注意:上部分代码注释掉的部分,使用addAttributes添加多个不起作用,使用addAttribute一个一个添加,亲测可用。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)