我做了一个简单的应用程序添加uibutton到collectionviewcell但是当我给出动作时会发生错误。这是一个截图。
和我的类代码: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
}
我的错误在哪里。你能帮助我吗 ?
答案 0 :(得分:0)
我已尝试将您的代码工作正常,请检查您是否对按钮以及自定义类名称进行操作
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
}
}
答案 1 :(得分:0)
答案 2 :(得分:-1)
你已经
了qIndex为? NSIndexPath 强>
你可以作为
qIndex为? Indexpath 强>
避免在cellforitem中进行不必要的向下转换。