Swift中UIView嵌套TableView不显示问题排查求助
Hey there! Let's figure out why your nested TableView isn't loading any content. I’ve spotted a couple of critical issues in your code that are causing this, plus I’ll share a cleaned-up implementation to get it working properly.
Key Problems in Your Current Code
1. TableView Instance Overwrite & Misplaced Delegate Setup
In your init(frame:) method, you first set the delegate/dataSource for the initial tableView property, but then in the setup() method, you create a new UITableView instance and overwrite the original one. This means the final tableView that gets added to your view has no delegate or dataSource assigned—so it never calls your data methods to load content.
2. Missing Initialization in init?(coder:)
Since you’re using an IBOutlet to connect TypeTableView in your ByType cell, your custom view is loaded from a xib/storyboard. This triggers the init?(coder:) initializer, but your current code doesn’t call setup() or configure the delegate/dataSource here. The tableView never gets set up at all in this case!
Corrected Implementation
Updated TypeTableView Code
import Foundation import UIKit class TypeTableView: UIView, UITableViewDataSource, UITableViewDelegate { var typesData = ["Videos","Images","Posts"] private var tableView: UITableView! // Only declare, initialize later override init(frame: CGRect){ super.init(frame: frame) backgroundColor = .red commonSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = .red commonSetup() } // Shared setup logic for both initializers private func commonSetup() { // Create the tableView here tableView = UITableView(frame: .zero, style: .grouped) tableView.backgroundColor = .red tableView.layer.cornerRadius = 10 tableView.translatesAutoresizingMaskIntoConstraints = false // Add to subview first (best practice before setting constraints) addSubview(tableView) // Activate constraints in a batch for cleaner code NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: topAnchor), tableView.leadingAnchor.constraint(equalTo: leadingAnchor), tableView.bottomAnchor.constraint(equalTo: bottomAnchor), tableView.trailingAnchor.constraint(equalTo: trailingAnchor) ]) // Assign delegate/dataSource to the newly created tableView tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return typesData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = typesData[indexPath.row] return cell } }
Updated ByType Cell Code
import UIKit class ByType: UITableViewCell { @IBOutlet var groupedTableView: TypeTableView! override func awakeFromNib() { super.awakeFromNib() separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15) layoutMargins = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15) // Adjust styling for the nested view if needed groupedTableView.layer.cornerRadius = 5 groupedTableView.layer.masksToBounds = true groupedTableView.layer.borderWidth = 0.5 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
Quick Optimization Tips
- Encapsulation: Mark the tableView as
privateto prevent external code from modifying it directly. - Constraint Best Practices: Use
NSLayoutConstraint.activateto batch constraints—it’s more efficient and readable. - Style Choice: If you don’t need grouped tableView features (like section headers/footers), consider using
.plainstyle instead for simplicity.
内容的提问来源于stack exchange,提问作者Aviav Sabag

