关于堆栈溢出的一篇文章已经解决了这个问题,但是它没有解决问题,因此可以解决。 implemented title attributed for row in picker view did not change the font?

为什么回调pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int)没有显示正确的字体。

这是我的代码:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    if component == 0 {
        print(keysDataSource[row])
        return keysDataSource[row]
    } else {
        print(chordsDataSource[row])
        return chordsDataSource[row]
    }

}


这是调试窗口中的结果,显示了调用该回调函数时print语句的结果:

vi{
    NSFont = "<UICTFont: 0x113d55700> font-family: \"Times New Roman\"; font-weight: normal; font-style: normal; font-size: 30.00pt";
}


该问题在屏幕截图中很明显。属性并不全部显示。显示基线偏移量属性,但不显示任何字体属性。而是显示系统字体。请注意b和L,它们应该分别显示为音乐扁平符号和音乐衰减符号。

ios - 为什么选择器 View 不显示属性字符串?-LMLPHP

最佳答案

丹尼尔·布劳

对标题使用两种方法,因为选择器视图是第一个titleForRow。

使用这样的代码。

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
       return pickerViewObj.keys[row]
    }

    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let attributedString = NSAttributedString(string: pickerViewObj.keys[row], attributes: [NSAttributedStringKey.foregroundColor : UIColor.black])
        return attributedString
    }


要么

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    let pickerLabel = UILabel()
    pickerLabel.font = UIFont.boldSystemFont(ofSize: 13)
    pickerLabel.textColor = UIColor.black
    pickerLabel.textAlignment = .center
    pickerLabel.text = "PickerView Cell Title"

    return pickerLabel
}


我希望这段代码能奏效。

10-07 18:57
查看更多