UIPickerView's “reusing view” always nil

2019-07-29 23:26发布

In my program I have custom view attached with each row of UIPickerView. But reusing view always comes nil. Hence every time new Custom View Object is creating. How can I use "reusing view"?

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        if let vv = view {
            return vv    // This will never getting called
        }

        let rowSize = pickerView.rowSize(forComponent: component)
        let pickerContentView = PickerContentView(frame: CGRect(x: 0, y: 0, width: rowSize.width, height: rowSize.height))
        pickerContentView.titleText = (items[Array(items.keys)[component]]! as [String])[row] as String + (component == 0 ? (row == 0 ? " MB" : " GB") : " vCPU")
        return pickerContentView
    }

UIView Subclass

class PickerContentView: UIView {

    // FIXME: - properties
    var titleText: String? {
        didSet {
            if let titleText = self.titleText {
                title.text = titleText
            }
        }
    }

    // FIXME: - initializer
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // FIXME: - create views
    private let title: Label = {
        let label = Label()
        label.textAlignment = .center
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: 17, weight: .regular)
        label.textColor = UIColor(hex: 0x212121, alpha: 1)
        label.fontSize = 17
        label.frameHeight = 44
        label.clipsToBounds = true
        return label
    }()

    // FIXME: - define constraints
    private func setupViews() {
        addSubview(title)

        // x, y, width, height => title
        addConstraints(format: "H:|-8-[v0]-8-|", views: title)
        addConstraints(format: "V:|[v0]|", views: title)

        layoutIfNeeded()
    }
}

1条回答
再贱就再见
2楼-- · 2019-07-30 00:05

Try this :

  func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
    if let vv = view {
        return vv    // This will never getting called
    }

    let rowSize = pickerView.rowSize(forComponent: component)
    let pickerContentView = PickerContentView(frame: CGRect(x: 0, y: 0, width: rowSize.width, height: rowSize.height))
    pickerContentView.titleText = (items[Array(items.keys)[component]]! as [String])[row] as String + (component == 0 ? (row == 0 ? " MB" : " GB") : " vCPU")
    view?.addSubview(pickerContentView)
    return view!
}
查看更多
登录 后发表回答