首页 > 解决方案 > 自定义 UIView 委托

问题描述

我是 swift 和 ios 开发的新手。我正在创建一个UIView由 a 组成的tableView,我将使用它来显示信息供用户选择,类似于选择器,但它是 atableView并且它占据了整个屏幕。

class SelectView: UIView, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet var contentView: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit(){
        Bundle.main.loadNibNamed("SelectView", owner: self, options: nil)
        //contentView.frame = self.bounds
        //contentView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        tableView.dataSource = self
        tableView.delegate = self
        self.addSubview(self.tableView)
    }



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let cell = UITableViewCell()
        print("cell ", String(indexPath.row))
        cell.textLabel?.text = "test"
        return cell
    }
}

然后在我的另一堂课中,我正在尝试这样做

let pickerView = SelectView()
pickerView.delegate = self
pickerView.datasource = self
textfield.inputView = pickerView

我认为这应该可以工作,但是会覆盖我放在 中的默认值SelectView,但是我收到了这个错误。

“ ”类型的值SelectView没有成员“ delegate”并且无法分配给属性:“ inputView”是仅获取属性。

不确定这里发生了什么,但似乎我已经委派了安全措施,然后只是用文本字段告诉班级委派。

标签: iosswift

解决方案


以这种方式检查,

import UIKit
public protocol menuOpen:  class {
    func openMenuAction(selectedValue : String)
}

class SelectView: UIView {
    open var delegate:menuOpen?
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.delegate.openMenuAction("test")
    }

}

现在在你的另一个班级

确保在你的另一个班级确认你的协议

class HomeViewController: UIViewController,menuOpen{

 override func viewWillAppear(_ animated: Bool) {
   let pickerView = SelectView()
    pickerView.delegate = self
    textfield.inputView = pickerView
}


func openMenuAction(selectedValue : String) {
//get your selected value here, you would better pass parameter in this method
}

    }

推荐阅读