【问题标题】:UIButton in CollectionViewCell "IndexPath doesn't work"CollectionViewCell 中的 UIButton“IndexPath 不起作用”
【发布时间】:2017-05-24 05:41:11
【问题描述】:

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

Error 1

Error 2

和我的类代码:UIbutton {}

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
}

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

【问题讨论】:

  • 您的keypadButton 插座未连接。
  • 在您的 stroyboard 中,您是否将按钮类设置为 KeypadUIButton ??

标签: swift xcode uibutton collectionview


【解决方案1】:

哦!我收到了你的错误,看来你错过了这个:

输入你的类名:KeypadUIButton

你也不需要在 swift 中使用 NSIndexPath。只需使用 IndexPath 代替。所以你不需要向下投射它。

【讨论】:

    【解决方案2】:

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

    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
    
    }
    
    }
    

    【讨论】:

      【解决方案3】:

      你拿走了

      qIndex 为? NSIndexPath

      你可以作为

      qIndex 为?索引路径

      它避免了在 cellforitem 中不必要的向下转换。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多