简体   繁体   中英

How to change font size of UIPickerView component in Swift?

when I change font color and size in attributedTitleForRow , font size does not changed, but selected row color changed:

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

and when I change font color and size in viewForRow method then all rows color change as well as font size:

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

    }

So, my question is that how to change font size for all rows but color change only selected row? as:

在此处输入图片说明

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

}

you can edit your code like this, and to see the label color changed, you have to add this code below. This is related to click event

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

       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM