我正在尝试子类化 UITableViewController 并通过重写 Controller 的 loadView()
方法执行自定义 View 设置。我这样做是因为我需要 TableView 顶部的 balanceView
和底部的 float 圆圈按钮。我做类似的事情,因为稍后我需要这个“基本” Controller 来用于不同的子类组,它们都必须具有这两个 View ,但它们将具有完全不同的 tableViews。一切都正确加载,但 viewDidLoad
和 viewDidAppear
中的 tableView
属性为零,但 tableViews 数据源和委托(delegate)方法调用成功!我做错了什么? (也许我需要子类化 UIViewController
?)这是我的代码:
这是我的 UITableViewController 子类 loadView:
override func loadView() {
super.loadView()
let bView = UIView()
balanceView = BalanceViewSwift()
balanceView.translatesAutoresizingMaskIntoConstraints = false
bView.addSubview(balanceView)
tableView = UITableView(frame: .zero, style: .plain)
tableView.translatesAutoresizingMaskIntoConstraints = false
bView.addSubview(tableView)
balanceView.addAnchorToSuperview(anchor: .top, margin: 0)
.addAnchorToSuperview(anchor: .leading, margin: 0)
.addAnchorToSuperview(anchor: .trailing, margin: 0).end()
tableView.addAnchorToSuperview(anchor: .bottom, margin: 0)
.addAnchorToSuperview(anchor: .leading, margin: 0)
.addAnchorToSuperview(anchor: .trailing, margin: 0).end()
balanceView.bottomAnchor.constraint(equalTo: tableView.topAnchor).isActive = true
addButtonView = CircleButton()
addButtonView.translatesAutoresizingMaskIntoConstraints = false
addButtonView.backgroundColor = .red
addButtonView.tintColor = .white
addButtonView.setTitle("+", for: .normal)
addButtonView.addTarget(self, action: #selector(BalanceTableViewController.addButtonTapped(_:)), for: .touchUpInside)
bView.addSubview(addButtonView)
addButtonView.addAnchorToSuperview(anchor: .bottom, margin: 16).addAnchorToSuperview(anchor: .trailing, margin: 16).end()
addButtonView.heightAnchor.constraint(equalTo: addButtonView.widthAnchor).isActive = true
addButtonView.widthAnchor.constraint(equalToConstant: 50).isActive = true
tableView.delegate = self
tableView.dataSource = self
balanceView.addFundsButtonIsHidden = !balanceViewAddFundsButtonIsVisible
addButtonView.isHidden = !circleBottomAddButtonIsVisible
view = bView
}
最佳答案
您需要删除super.loadView()
You can override this method in order to create your views manually. If you choose to do so, assign the root view of your view hierarchy to the view property. The views you create should be unique instances and should not be shared with any other view controller object. Your custom implementation of this method should not call super. Apple doc
关于ios - 创建子类并覆盖 loadView() 时 UITableViewController.tableView=nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51036061/