Swift “CollectionViewCell中的UI按钮”;indexath不';t工作“;
我制作了一个简单的应用程序,将uibutton添加到collectionviewcell,但当我执行操作时,会发生错误。这是一个截图 我的类代码是:UIbuton{}Swift “CollectionViewCell中的UI按钮”;indexath不';t工作“;,swift,xcode,uibutton,collectionview,Swift,Xcode,Uibutton,Collectionview,我制作了一个简单的应用程序,将uibutton添加到collectionviewcell,但当我执行操作时,会发生错误。这是一个截图 我的类代码是:UIbuton{} import Foundation import UIKit class KeypadUIButton: UIButton { var qIndex : NSIndexPath? } 我的手机课程是: import UIKit class ConverterCollectionViewCell: UICollec
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
}
我的错误在哪里。你能帮我吗 你已经
qIndex作为?nsindepath
你可以当作
qIndex作为?indexath
它避免了cellforitem中不必要的降级。我已尝试使用您的代码。它工作正常,请检查您是否为按钮提供了操作以及为按钮提供了自定义类名
哦!!我知道你的错误了,看来你错过了这个: 键入类名:KeypadUIButton
此外,您不需要在swift中使用NSIndexPath。只需使用indexath即可。因此,您无需按下按钮。您的
keypadButton
插座未连接。在stroyboard中,您是否将按钮类设置为KeypadUIButton
??
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
}
}