如何在Swift中更改UIPickerView组件的字体大小?

问题描述:

当我改变在attributedTitleForRow字体颜色和大小,字体大小不会改变,但选择的行的颜色变化:如何在Swift中更改UIPickerView组件的字体大小?

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { 
     var color: UIColor! 
     var size: UIFont! 
       switch component { 
     case 0: 
      if pickerView.selectedRow(inComponent: 0) == row { 
       color = UIColor.init(red: 186/255, green: 61/255, blue: 62/255, alpha: 1.0) 
       size = UIFont(name:"Raleway", size:14) 

      } else { 
       color = UIColor.black 
      } 

      let attributes: [String: AnyObject] = [ 
       NSForegroundColorAttributeName: color, NSFontAttributeName: size] 
      return NSAttributedString(string: peopleCount[row], attributes: attributes) 
     default: 
      return NSAttributedString() 
     } 
    } 

和当我改变字体颜色和大小在viewForRow方法然后所有行的颜色变化以及字体大小:

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { 

     var label = view as! UILabel! 
     if label == nil { 
      label = UILabel() 
      label?.textColor = UIColor.red 
     } 
     switch component { 
     case 0: 

      label?.text = peopleCount[row] 
      label?.font = UIFont(name:"Raleway", size:14) 
      return label! 
     default: 
      return label! 
     } 

    } 

所以,我的问题是,如何更改所有行的字体大小,但颜色只改变选定的行?如:

enter image description here

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { 

    var label = view as! UILabel! 
    if label == nil { 
     label = UILabel() 
     label?.textAlignment = .center 
     //label?.textColor = UIColor.red 
    } 
    switch component { 
    case 0: 

      label?.text = peopleCount[row] 
      if(pickerView.selectedRow(inComponent: 0)==row){ 
      label?.textColor = UIColor.red 
      } 
      return label! 

    default: 
     return label! 
    } 

} 

你可以编辑你这样的代码,并看到标签的颜色改变,你必须在下面添加以下代码。这与点击事件有关

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { 
    pickerView.reloadAllComponents() 

     }