I use a xib file to build a UIView called SelectView which has a button and a tableView inside it. Code shows below
@IBOutlet weak var selectTableView: UITableView!
@IBOutlet weak var notSureButton: UIButton!
and I programmatically set the tableView's delegate and datasource inside the function awakeFromNib(), code below
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")
}
When I run the app ,it crash at the awakeFromNib, because the selectTableView was nil.
the code of the class SelectView below
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
}
}
I load the view inside the ViewController's viewDidLoad function
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)
}