XZ

XZ,第1张

直接使用代理方法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一个一个添加,亲测可用。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/996778.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存