UIPickerView" s"重用视图"永远没有

时间:2017-04-13 09:45:49

标签: ios iphone swift uiview swift3

在我的程序中,我有自定义视图附加UIPickerView的每一行。但重用视图总是没有。因此,每次创建新的自定义视图对象时。我如何使用"重复使用视图"?

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 个答案:

答案 0 :(得分:0)

试试这个:

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