首页 > 解决方案 > UIButton Array - 每个按钮都指向 CollectionView swift 中的标记 0

问题描述

我正在以编程方式设计我的 UI,我正在创建一些按钮,然后在 UICollectionView 中显示。当我检查时在 UICollectionView 中显示后,每个按钮都指向标记 0。这是我的完整代码代码。

class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{
var buttonsArray = [UIButton]()
    let buttonsName = ["Start Trade", "Wallet","Profile",  "My Portfolio", "Dashboard","My Transactions","My Blotter" ,"My Reports", "Forum"]
    let buttonImages = ["1","2","3", "4", "5", "6", "7","8", "9"]

    var collectionview: UICollectionView!
    var cellId = "Cell"


    override func viewDidLoad() {
        super.viewDidLoad()
                for i in 0..<9 {
                let btn = UIButton()
                btn.tag = i
                btn.frame = CGRect(x: btn.frame.width/2, y:btn.frame.width/2, width: 106, height: 97)
                btn.backgroundColor = UIColor(red: 0.15, green: 0.22, blue: 0.68, alpha: 0.86)
                btn.layer.cornerRadius = 5
                btn.titleLabel?.font =  UIFont.setFont(of: 12)
                btn.addTarget(self, action: #selector(pressedAction(_:)), for: .touchUpInside)
                btn.setTitleColor(UIColor(red: 0.82, green: 0.56, blue: 0.23, alpha: 1), for: .normal)
                btn.setTitle(buttonsName[i], for: .normal)

                btn.translatesAutoresizingMaskIntoConstraints = false
                buttonsArray.append(btn)

        }

  let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.itemSize = CGSize(width: 106, height: 97)

        collectionview = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        collectionview.dataSource = self
        collectionview.delegate = self
        collectionview.register(MainDashBoardCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        collectionview.showsVerticalScrollIndicator = false
        collectionview.backgroundColor = view.backgroundColor
        self.view.addSubview(collectionview)

   }


 @objc func pressedAction(_ sender: UIButton) {
        // do your stuff here
        sender.animateButton(sender: sender)
        print(sender.tag)
    }

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

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell = collectionview.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MainDashBoardCollectionViewCell
        cell.images.image = buttonImages[indexPath.item]
        cell.button = buttonsArray[indexPath.item]
        cell.Label0.text = buttonsName[indexPath.item]
        return cell
    }

这是我的 CollectionViewCell 类

import UIKit


class MainDashBoardCollectionViewCell: UICollectionViewCell {
    var button :UIButton = {
        let btn = UIButton()
        btn.frame = CGRect(x: btn.frame.width/2, y:btn.frame.width/2, width: 106, height: 97)
        btn.backgroundColor = UIColor(red: 0.15, green: 0.22, blue: 0.68, alpha: 0.86)
        btn.layer.cornerRadius = 5
        btn.addTarget(self, action: #selector(pressedAction(_:)), for: .touchUpInside)
        btn.titleLabel?.font =  UIFont.setFont(of: 12)
        btn.setTitleColor(UIColor(red: 0.82, green: 0.56, blue: 0.23, alpha: 1), for: .normal)
        btn.translatesAutoresizingMaskIntoConstraints = false
        return btn
    }()
    var images: UIImageView = {
        let imgV = UIImageView()
        imgV .translatesAutoresizingMaskIntoConstraints = false
        return imgV
    }()
    let Label0: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 60, height: 15)
        label.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        label.text = ""
        label.font = UIFont.setFont(of: 12)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(images)
        addSubview(button)
        addSubview(Label0)
        shared()
    }
    @objc func pressedAction(_ sender: UIButton) {
        // do your stuff here
        print("clicked")
        print("you clicked on button \(sender.tag)")
    }
func shared() {
    self.contentView.addSubview(button)
    self.contentView.addSubview(images)
    NSLayoutConstraint.activate([
        button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0),
        button.topAnchor.constraint(equalTo: contentView.topAnchor, constant:   0),
        button.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0),
        button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0),
        ])
    images.widthAnchor.constraint(equalToConstant: 26).isActive = true
    images.heightAnchor.constraint(equalToConstant: 28).isActive = true
    images.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
    images.centerYAnchor.constraint(equalTo: button.centerYAnchor, constant: -10).isActive = true

    Label0.centerXAnchor.constraint(equalTo: images.centerXAnchor).isActive = true
    Label0.centerYAnchor.constraint(equalTo: button.centerYAnchor, constant: 20).isActive = true

}




required init?(coder aDecoder: NSCoder) {
    //super.init(aDecoder)
    fatalError("init(coder:) has not been implemented")

   }
}

我的代码有什么问题吗?请帮我修复它。提前致谢。

标签: iosarraysswiftuicollectionviewuibutton

解决方案


默认情况下,每个 UI 组件都有标签 0,因此您必须更改每个按钮的标签。

试试这个cellForItem

cell.button.tag = indexPath.row

推荐阅读