ios - 如何在 Swift 中更改 UIPickerView 组件的字体大小?

标签 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

最佳答案

    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/

相关文章:

ios - 在 iOS 上使用 NSMutableAttributedString 对同一标签进行多文本对齐

ios - 如何在 collectionView 或 tableView 单元格中重复动画?

ios - UIPickerView 有两行

swift - 连接多个UIPickerView时,出现titleForRow错误

ios - 在容器中使用 UICollectionViewController - Swift

按钮上带有 PNG 的 iOS 抗锯齿

ios - 不要删除 UITable 的第一行

ios - 自定义选项卡栏以在 View Controller 之间导航

arrays - 某些数据更改后如何刷新 TableView?

ios - 在 UIPickerView 中重新加载数据和组件