我有一个以编程方式编写的tableView。我初始化了部分和行的大小。我还将一个containerView放在情节提要中,其中将包含tableView。我的问题是,我的表格视图无法正确滚动。
这是我的故事板:
这是我在情节提要中的视图的出口:
@IBOutlet weak var trainingDetailsContainerView: UIView!
这是我初始化的表:
var moduleLessonsTableView: UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
// tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = Themes.gray_dec
tableView.sectionHeaderHeight = 35
tableView.rowHeight = 50
tableView.isScrollEnabled = true
tableView.register(TrainingModulesTableViewCell.self, forCellReuseIdentifier: "ModuleLessonsCell")
return tableView
}()
这是我要设置tableView,高度和所有位置的位置:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
moduleLessonsTableView.frame = CGRect(x: 0, y: 0, width: trainingDetailsContainerView.frame.width, height: trainingDetailsContainerView.frame.height)
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
}
我可以尝试将其放到viewWillAppear中,并且高度将正确呈现,这使我意识到,trainingDetailsContainerView的边界是在其他视图之前设置的。但是问题在于它会突然弹出。我真的不希望这样,因为从用户的角度来看这似乎是一个滞后。
任何帮助将不胜感激。
我也无法标记视图生命周期,所以我将其放在此处。
尝试在viewDidLoad
中向表视图添加约束,而不是设置框架。同时从viewWillAppear
方法中删除代码。示例代码:
override func viewDidLoad() {
super.viewDidLoad()
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
moduleLessonsTableView.topAnchor.constraint(equalTo: trainingDetailsContainerView.topAnchor).isActive = true
moduleLessonsTableView.leadingAnchor.constraint(equalTo: trainingDetailsContainerView.leadingAnchor).isActive = true
moduleLessonsTableView.trailingAnchor.constraint(equalTo: trainingDetailsContainerView.trailingAnchor).isActive = true
moduleLessonsTableView.bottomAnchor.constraint(equalTo: trainingDetailsContainerView.bottomAnchor).isActive = true
}
我已经检查了-这个ViewController应该可以工作:
class ViewController: UIViewController {
@IBOutlet weak var trainingDetailsContainerView: UIView!
var moduleLessonsTableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = Themes.gray_dec
tableView.sectionHeaderHeight = 35
tableView.rowHeight = 50
tableView.isScrollEnabled = true
tableView.register(TrainingModulesTableViewCell.self, forCellReuseIdentifier: "ModuleLessonsCell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
moduleLessonsTableView.topAnchor.constraint(equalTo: trainingDetailsContainerView.topAnchor).isActive = true
moduleLessonsTableView.leadingAnchor.constraint(equalTo: trainingDetailsContainerView.leadingAnchor).isActive = true
moduleLessonsTableView.trailingAnchor.constraint(equalTo: trainingDetailsContainerView.trailingAnchor).isActive = true
moduleLessonsTableView.bottomAnchor.constraint(equalTo: trainingDetailsContainerView.bottomAnchor).isActive = true
}
}