【问题标题】:How can I add image in UITableView section header using swift?如何使用 swift 在 UITableView 部分标题中添加图像?
【发布时间】:2020-03-20 01:39:11
【问题描述】:

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

这些是我的头数组;

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

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

【问题讨论】:

    标签: ios swift uitableview header uiimageview


    【解决方案1】:

    您必须确认一些 UITableViewDataSourceUITableViewDelegate 方法。

    要声明节数调用func numberOfSections(in tableView: UITableView) -> Int方法

    在Section Header中显示图片调用func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?方法

    如果要设置节头的高度调用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
    }
    
    

    【讨论】:

    • 好吧,如果我创建一个这样的数组,""" sectionImages: [[UIImages]] = [[picture1],[picture2],[picture3],[picture4],[picture5]]
    • 如何在这个数组中添加标题
    • sectionImages是不是UIImage的数组?
    • 数组应该是这样的sectionImages: [UIImage] = [picture1, picture2, picture3, picture4]
    • 很抱歉我写错了。我的问题是如何将这个 sectionImages 用于标题图像
    猜你喜欢
    • 1970-01-01
    • 2015-04-20
    • 2023-03-06
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    相关资源
    最近更新 更多