@IBOutlet UITableView!当我在函数awakeFromNib()中设置它的委托时是nil

时间:2017-08-05 16:33:18

标签: ios uitableview null awakefromnib

我使用xib文件构建一个名为SelectView的UIView,它里面有一个按钮和一个tableView。代码如下所示

@IBOutlet weak var selectTableView: UITableView!
@IBOutlet weak var notSureButton: UIButton!

我以编程方式在函数awakeFromNib()中设置tableView的委托和数据源,代码如下

override func awakeFromNib() {
    super.awakeFromNib()
    selectTableView.delegate = self
    selectTableView.dataSource = self
    let nib = UINib(nibName: "SelectCell", bundle: nil)
    self.selectTableView.register(nib, forCellReuseIdentifier: "select cell")
}

当我运行应用程序时,它会在awakeFromNib处崩溃,因为selectTableView是nil。

下面的SelectView类的代码

class SelectView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    override func awakeFromNib() {
        super.awakeFromNib()
        selectTableView.delegate = self
        selectTableView.dataSource = self
        let nib = UINib(nibName: "SelectCell", bundle: nil)
        self.selectTableView.register(nib, forCellReuseIdentifier: "select cell")
    }

    var controller: LearnViewController?
    @IBOutlet weak var selectTableView: UITableView!
    @IBOutlet weak var notSureButton: UIButton!
}

extension SelectView: UITableViewDataSource, UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = selectTableView.dequeueReusableCell(withIdentifier: "select cell", for: indexPath) as! SelectCell
        if let vc = controller{
            cell.indexLabel.text = String((vc.selectIndex[indexPath.row]) + ".")
            cell.cardSuitImageView.image = UIImage(named: vc.cardSuitArray[indexPath.row])
            cell.cardNumberLabel.text = vc.cardNumberArray[indexPath.row]
            cell.cardNumberLabel.text = vc.cardNumberArray[indexPath.row]
        }
        return cell
    }

}

我在ViewController的viewDidLoad函数

中加载视图
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    selectView = Bundle.main.loadNibNamed("SelectView", owner: self, options: nil)![0] as! SelectView
    selectView.controller = self
    selectBaseView.addSubview(selectView)
}

0 个答案:

没有答案