2016-12-17 4 views
1

Schrift ändern in meinem picker Versuch NSAttributedString mit:Schrift NSAttributedString mit Einstellung

public func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { 
    guard let castDict = self.castDict else { 
     return nil 
    } 
    let name = [String](castDict.keys)[row] 
    switch component { 
    case 0: 
     return NSAttributedString(string: name, attributes: [NSForegroundColorAttributeName : AppColors.Rose.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]) 
    case 1: 
     guard let character = castDict[name] else { 
      return NSAttributedString(string: "Not found character for \(name)", attributes: [NSForegroundColorAttributeName : AppColors.Rose.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]) 
     } 
     return NSAttributedString(string: character, attributes: [NSForegroundColorAttributeName : AppColors.LightBlue.color, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)]) 
    default: 
     return nil 
    } 
} 

Farbe geändert, Schriftart - nicht:

enter image description here

Was mache ich falsch?

Antwort

1

Die kurze Antwort wäre, dass Sie nichts falsch machen, es ist ein Problem von Apple, da sie nirgendwo geschrieben haben, dass Fonts nicht in einem UIPickerView geändert werden können.

Es gibt jedoch eine Problemumgehung.

Von der UIPickerViewDelegate müssen Sie func pickerView(_ pickerView:, viewForRow row:, forComponent component:, reusing view:) -> UIView implementieren. Mit dieser Implementierung können Sie eine benutzerdefinierte UIView für jede Zeile bereitstellen.

Hier ist ein Beispiel:

func pickerView(_ reusingpickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { 
    if let pickerLabel = view as? UILabel { 
     // The UILabel already exists and is setup, just set the text 
     pickerLabel.text = "Some text" 

     return pickerLabel 
    } else { 
     // The UILabel doesn't exist, we have to create it and do the setup for font and textAlignment 
     let pickerLabel = UILabel() 

     pickerLabel.font = UIFont.boldSystemFont(ofSize: 18) 
     pickerLabel.textAlignment = NSTextAlignment.center // By default the text is left aligned 

     pickerLabel.text = "Some text" 

     return pickerLabel 
    } 
} 
+0

Dank für die ausführliche Antwort. Ja, mit der benutzerdefinierten Ansicht. Versuchen Sie immer, keine Ansichten zum Zweck der Leistung zu verwenden – zzheads