首页 > 解决方案 > 如何使用结构中的数据更改按钮的文本?

问题描述

所以我正在尝试使用我定义的结构更改 UICollectionView 单元格中按钮的文本,但我不知道该怎么做,有什么帮助吗?我已经尝试了一些事情,比如 didSet 并在那里更改了文本,但它没有用

struct customData {
    var screenName: String
}
class orderViewController: UIViewController {
    let data = [
        customData(screenName: "Home"),
        customData(screenName: "Search"),
        customData(screenName: "Previous Orders"),
        customData(screenName: "Profile")
    ]
}
class customCell: UICollectionViewCell {
    
    var data: customData? {
        didSet {
            guard let data = data else {return}
            tabBar.titleLabel?.text = data.screenName
        }
    }
    fileprivate let tabBar: UIButton = {
        let segueButton = UIButton()
        segueButton.backgroundColor = .clear
        segueButton.layer.cornerRadius = 15
        segueButton.layer.cornerCurve = .continuous
        segueButton.setTitle("Test", for: .normal)
        segueButton.titleLabel?.font = FontKit.roundedFont(ofSize: 45, weight: .semibold)
        return segueButton
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(tabBar)
        tabBar.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
        tabBar.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
        tabBar.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
        tabBar.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
        tabBar.frame = CGRect(x: 0, y: 0, width: contentView.frame.width, height: contentView.frame.height)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

标签: swift

解决方案


修复它,在我的 didSet 函数中,我将函数更改为 tabBar.setTitle(data.screenName, for: .normal) 并设置它


推荐阅读