OStack程序员社区-中国程序员成长平台

标题: ios - 如何在 Swift 中更改 UIPickerView 组件的字体大小? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:48
标题: ios - 如何在 Swift 中更改 UIPickerView 组件的字体大小?

当我在 attributedTitleForRow 中更改字体颜色和大小时,字体大小不会改变,但选定的行颜色会改变:

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



Best Answer-推荐答案


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

       }

关于ios - 如何在 Swift 中更改 UIPickerView 组件的字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44383150/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4