簡體   English   中英

操縱可重用單元中的標簽?

[英]Manipulating tags inside reusable cells?

在SO的幫助下,我設法為單元內的按鈕提出了這種方法。

CellForRowAtIndexPath

    let cell = tableView.dequeueReusableCellWithIdentifier("buildCell", forIndexPath: indexPath) as! UITableViewCell

    let mapsbut = cell.viewWithTag(912) as! UIButton
    mapsbut.tag = indexPath.row
    mapsbut.addTarget(self, action: "mapsHit:", forControlEvents: UIControlEvents.TouchUpInside)

    return cell

ViewController

func mapsHit(sender: UIButton!){

    passBuild = buildings[sender.tag]
    performSegueWithIdentifier("mapSegue2", sender: self)

}

現在發生的是,當我在“表格視圖”中滾動時,在行上看到一個致命錯誤:

let mapsbut = cell.viewWithTag(912) as! UIButton

與消息: unexpectedly found nil while unwrapping an Optional value

因此,正在發生的事情是,視圖標記在函數內部發生了變化,當我嘗試在下一個單元格中引用它時,已更改了912

為了解決這個問題,我在mapsHit函數的末尾添加了這行代碼

sender.tag = 912

但是現在我需要滿足以下條件:

if the button isn't clicked, change tag to 912

這似乎不可能。

有什么解決方法嗎?

像這樣設置您的自定義單元:

buildingCell

class buildingCell: UITableViewCell {

    @IBOutlet weak var mapsbut: UIButton!

}

CellForRowAtIndexPath

    let cell = tableView.dequeueReusableCellWithIdentifier("buildCell", forIndexPath: indexPath) as! buildingCell

    cell.mapsbut.tag = indexPath.row
    cell.mapsbut.addTarget(self, action: "mapsHit:", forControlEvents: UIControlEvents.TouchUpInside)

    return cell

並使您的mapsHit函數完全相同。

這樣,您不必擔心初始參考的Tag,因此不會遇到任何nil錯誤!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM