簡體   English   中英

如何使用 swift 在 UITableView 部分標題中添加圖像?

[英]How can I add image in UITableView section header using swift?

我有一個 4 標題。 我想在標題旁邊添加一個圖像。

這些是我的標題數組;

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

如何使用 swift 在 UITableView 部分標題中添加圖像?

您必須確認一些UITableViewDataSourceUITableViewDelegate方法。

要聲明節數,請調用func numberOfSections(in tableView: UITableView) -> Int方法

要在部分標題中顯示圖像,請調用func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? 方法

如果要設置section header的高度,調用func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat方法。

viewForHeaderInSection方法中,您可以設計標題。 並且不要忘記設置AutoLayoutConstraint

您可以創建一個 UIImage 數組以在節標題中顯示圖像,如下所示

let sectionImages: [UIImage] = [picutre1, picture2, picture3, picture4]

這是完整的代碼。


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 = sectionImages[section]
    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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM