繁体   English   中英

CollectionViewCell中的UIButton“ IndexPath不起作用”

[英]UIButton in CollectionViewCell “IndexPath doesn't work”

我做了一个简单的应用程序,将uibutton添加到collectionviewcell,但是当我执行操作时会发生错误。 这是一个屏幕截图。

错误1

错误2

和我的课程代码:UIbuton {}

import Foundation
import UIKit

class KeypadUIButton: UIButton {
    var qIndex : NSIndexPath?
}

我的细胞班级是:

import UIKit

class ConverterCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var keypadButton: KeypadUIButton!
}

和错误:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = padCollectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ConverterCollectionViewCell
        let index = indexPath.row
       // -> cell.keypadButton.qIndex = indexPath as NSIndexPath
return cell
}

我的错在哪里 你能帮助我吗 ?

我尝试使用您的代码正常工作,请检查按钮是否已执行操作以及按钮的自定义类名称 自定义按钮

class KeypadUIButton: UIButton {
   var qIndex : NSIndexPath?
}

class ConverterCollectionViewCell: UICollectionViewCell {

   @IBOutlet weak var keypadButton: KeypadUIButton!
}

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from 
    a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

extension ViewController : UICollectionViewDataSource{

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 16
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let identifier : String = "test"
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ConverterCollectionViewCell
    cell.keypadButton.qIndex = indexPath as NSIndexPath?
    cell.keypadButton.setTitle("\(indexPath.row + 1)", for: .normal)

    return cell

}

}

哦! 我有您的错误,看来您错过了:

自定义类别名称

输入您的班级名称:KeypadUIButton

另外,您无需快速使用NSIndexPath。 只需使用IndexPath即可。 因此,您无需将其转换。

你拿了

qIndex为? NSIndexPath

你可以当作

qIndex为? 索引路径

它避免了cellforitem中不必要的下降。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM