我有4个标题。我想在标题旁边添加图片。
这些是我的标题数组;
let sections: [String] = ["Cleaning","Computer Repair", "Electircity", "Painting", "Plumbing"]
如何使用swift在UITableView节标题中添加图像?
您必须确认一些UITableViewDataSource和UITableViewDelegate方法。
要声明段数,请调用func numberOfSections(in tableView: UITableView) -> Int
方法
在节标题调用func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
方法中显示图像
如果要设置段标题的高度,请调用func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat
方法。
在viewForHeaderInSection
方法中,您可以设计标题。并且不要忘记设置AutoLayoutConstraint
这是完整的代码。
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let imageView = UIImageView()
imageView.image = UIImage(named: "finn")
let headerView = UIView()
headerView.backgroundColor = .white
headerView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.centerXAnchor.constraint(equalTo: headerView.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 60).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 60).isActive = true
return headerView
}