2017-05-24 18 views
0

我做了一個簡單的應用程序添加uibutton到collectionviewcell,但是當我給行動一個錯誤發生。這是一個屏幕截圖。CollectionViewCell中的UIButton「IndexPath不起作用」

Error 1

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

我的錯誤在哪裏?你可以幫我嗎 ?

+0

您的'keypadButton'插座未連接。 – rmaddy

+0

在您的stroyboard中,您是否將按鈕類設置爲'KeypadUIButton'? – Bilal

回答

0

哦!我有你的錯誤,看來你錯過了這個:

Custom class name

鍵入您的類名:KeypadUIButton

而且你不需要在迅速使用NSIndexPath。只需使用IndexPath即可。所以你不需要投下它。

-1

您已經採取

qIndex作爲? NSIndexPath

你可以採取如

qIndex作爲? Indexpath

它避免了cellforitem中不必要的向下轉換。

0

我有你的代碼嘗試它的做工精細,請你給行動,您的按鈕以及自定義類名的按鈕custom button

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 

} 

} 
相關問題