0

I am currently creating a custom view. This view has a UITableView with it. The delegate for this control will be the backing class for the custom control.

class MyView: UIView {

    @IBOutlet weak var autoCompleteView: UITableView!

}

extension MyView: UITableViewDelegate {

}

extension MyView: UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath)
        cell.textLabel!.text =  "\(indexPath.row) - Its working"
        return cell
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

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

Now at some point here, in this class, I need to get the delegate for the UITableView but that can only happen once the view has been loaded (otherwise autoCompleteView will be nil).

If it were in a UIViewController I could simply add it to viewDidLoad but I dont have that open here. So how can I go about setting the delegate for the UITableView

David Pilkington
  • 13,528
  • 3
  • 41
  • 73

2 Answers2

1

Now at some point here, in this class, I need to get the delegate for the UITableView but that can only happen once the view has been loaded

I am not entirely sure what you mean by that. The view MyView is loaded if you are inside a method of it. If the class would not be there, it could not be calling a method of it. So if you configure things in initWithFrame: everything should be fine.

The only thing I can think of otherwise is if your view is layed out in Interface Builder and thus will be decoded. In that case, while the view might already be loaded, some references might not be. For this, you will get a call to awakeFromNib after all decoding has completed.

Michael Ochs
  • 2,846
  • 3
  • 27
  • 33
0

//you can try these

class MyView: UIView {
    @IBOutlet weak var autoCompleteView: UITableView!

    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
    }

    override func didMoveToSuperview() {
        super.didMoveToSuperview()
    }
}
Berlin Raj
  • 124
  • 6