将变量传递到自定义 UITableViewHeaderFooterView

问题描述 投票:0回答:1

有一个

UIViewController
包含
UITableView

class ProfileViewController: UIViewController {

    private lazy var profileView: ProfileHeaderView = {
        let profileView = ProfileHeaderView()
        return profileView
    }()
    
    private lazy var feedView: UITableView = {
        let feedView = UITableView().feedView(isHeaderHidden: true)
        feedView.isUserInteractionEnabled = true
        feedView.allowsSelection = true
        return feedView
    }()
...
}

在这个

UITableView
中有一个自定义标头(自定义类
ProfileHeaderView
符合协议
UITableViewHeaderFooterView
),它是这样实现的:

extension ProfileViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            if let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ProfileHeaderView") as? ProfileHeaderView {
                view.isUserInteractionEnabled = true
                return view
            }
        }
        return nil
    }
}    

假设我们的

ProfileHeaderView
有一个变量(例如字符串)。如何将此变量的值从我们的
UIViewController
传递到我们的自定义标头中?

编辑 这是

ProfileHeaderView
声明的快速浏览:

class ProfileHeaderView: UITableViewHeaderFooterView {
        
    public var statusText: String?
    
     override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        addSuviews()
        setupConstraints()
        changeBackgroundColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addSuviews()
        setupConstraints()
        changeBackgroundColor()
    }
    
    ...
}
ios swift uitableview uiviewcontroller uikit
1个回答
0
投票

只需为

statusText
赋值即可。

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        if let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ProfileHeaderView") as? ProfileHeaderView {
            view.isUserInteractionEnabled = true
            view.statusText = "some status text for section 0"
            return view
        }
    }
    return nil
}

但是当

statusText
更改时,您还需要让标题视图更新标签或其他一些 UI 组件。

class ProfileHeaderView: UITableViewHeaderFooterView {
    public var statusText: String? {
        didSet {
            someLabel.text = statusText // update the UI as needed
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.