如何使用swift在UITableView节标题中添加图像?

问题描述 投票:-2回答:1

我有4个标题。我想在标题旁边添加图片。

这些是我的标题数组;

let sections: [String] = ["Cleaning","Computer Repair", "Electircity", "Painting", "Plumbing"]

如何使用swift在UITableView节标题中添加图像?

ios swift uitableview header uiimageview
1个回答
0
投票

您必须确认一些UITableViewDataSourceUITableViewDelegate方法。

要声明段数,请调用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
}

© www.soinside.com 2019 - 2024. All rights reserved.