您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

以下pickerView:attributedTitleForRow:forComponent:方法实现应为您提供帮助:

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

如果要attributedString在多个ifswitch语句中使用,下面的UIViewControllersubClass示例将为您提供帮助:

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
        }
    }

}
Swift 2022/1/1 18:15:56 有296人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶