iOS Swift 中带有普通和粗体文本标签的选择器视图

iOS picker view with normal and bold text labels in Swift

我需要一个包含一些条目的选择器视图,这些条目具有正常的字体粗细,而一些具有粗体粗细。找出如何创建属性字符串不是问题,所以我将所有内容放在一起但看不出有什么不同。第一行不是粗体也不是更大。不过,不同的颜色确实有效。

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

    let darkColor = UIColor.blackColor()
    let lightColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3)                             
    if row == 0 {
        return NSAttributedString(string: "first row bold and black", attributes: [NSForegroundColorAttributeName:darkColor, NSFontAttributeName : UIFont.boldSystemFontOfSize(20)])
    } else {
        return NSAttributedString(string: "other rows gray and normal", attributes: [NSForegroundColorAttributeName:lightColor])
    }
}

你能试试这个代码吗?

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"first row bold and black"];
NSRange selectedRange = NSMakeRange(0, string.length);

[String beginEditing];
[String addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:selectedRange];
[String endEditing];

使用 viewForRow,而不是 attributedTitleForRow,您可以获得更多的控制权

func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView
{
    let pickerLabel = UILabel()

    if row == 0
    {
        pickerLabel.text = "first row bold and black"
        pickerLabel.textColor = UIColor.blackColor()
        pickerLabel.font = UIFont.boldSystemFontOfSize(20)
    }
    else
    {
        pickerLabel.text = "other rows gray and normal"
        pickerLabel.textColor = UIColor.grayColor()
    }

    pickerLabel.textAlignment = NSTextAlignment.Center
    return pickerLabel
}