如何在uicollection视图中设置我的UIButton标题

时间:2019-04-08 19:27:31

标签: ios swift uicollectionview uibutton

所以我想用我的数组设置我的按钮标题,但是结果按钮标题没有显示我的数组

// viewcontroller

let menus = ["Topokki","Sundubu","Galbitang"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return menus.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell



    cell.menusButton.titleLabel?.text = menus[indexPath.item]

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print(indexPath.item)
}

// collectionviewcell类

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var menusButton: UIButton!


}

2 个答案:

答案 0 :(得分:0)

尝试:

cell.menusButton.setTitle(menus[indexPath.item], forState: .normal)

答案 1 :(得分:0)

摘自UIButton中约titleLabel的文档

  

要设置标签的实际文本,请使用setTitle(_:for:)button.titleLabel.text不允许您设置文本)

所以...您需要通过调用setTitle(_:for:)

来设置按钮的标题
cell.menusButton.setTitle(menus[indexPath.item], for: .normal)