且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift中使用多个组件更改UIPickerView的文本颜色?

更新时间:2022-04-25 01:15:21

关注 pickerView:attributionTitleForRow:forComponent:方法实现应该可以帮助你:

The following pickerView:attributedTitleForRow:forComponent: method implementation should help you:

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let attributedString = NSAttributedString(string: "some string", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
    return attributedString
}

更新

如果你想使用 attributionString 在多个如果切换语句中,以下 UIViewController subClass示例将帮助您:

If you want to use attributedString in multiple if or switch statements, the following UIViewController subClass example will help you:

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var picker: UIPickerView!

    let arrayOne = ["One", "Two", "Three", "Four", "Five", "Six"]
    let arrayTwo = ["Un", "Deux", "Trois", "Quatre", "Cinq", "Six"]
    let arrayThree = [1, 2, 3, 4, 5, 6]


    override func viewDidLoad() {
        super.viewDidLoad()

        picker.delegate = self
        picker.dataSource = self
    }

    func numberOfComponentsInPickerView(_: UIPickerView) -> Int {
        return 3
    }

    func pickerView(_: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch component {
        case 0:
            return arrayOne.count
        case 1:
            return arrayTwo.count
        case 2:
            return arrayThree.count
        default:
            return NSNotFound
        }
    }

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

        switch component {
        case 0:
            attributedString = NSAttributedString(string: arrayOne[row], attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
        case 1:
            attributedString = NSAttributedString(string: arrayTwo[row], attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
        case 2:
            attributedString = NSAttributedString(string: toString(arrayThree[row]), attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
        default:
            attributedString = nil
        }

        return attributedString
    }

    func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch component {
        case 0:
            println(arrayOne[row])
        case 1:
            println(arrayTwo[row])
        case 2:
            println(arrayThree[row])
        default:
            break
        }
    }

}