簡體   English   中英

swift-Tableview單元格UIButton背景色

[英]swift-Tableview cell UIButton background color

使用具有表格視圖的應用程序。 在每個單元格中都有兩個按鈕(通過/失敗)。 如果用戶點擊“確定”,則通過的背景將變為綠色,而“!” 失敗,背景變為紅色。 我遇到的問題是,如果連續點擊了一個按鈕(假設失敗按鈕)。 滾動淹沒到另一行(如向下5行)。 故障按鈕的背景色也已更改(紅色)。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: CellTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell") as! CellTableViewCell

    if cell == nil
    {
        cell = CellTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        cell.textLabel?.text = myArray[indexPath.row]
        cell.fail.tag = indexPath.row
        cell.fail.addTarget(self, action: #selector(ViewController.errorBtn(_:)), for: .touchUpInside)
    }
    else
    {
        cell.textLabel?.text = myArray[indexPath.row]
        cell.fail.tag = indexPath.row
        cell.fail.addTarget(self, action: #selector(ViewController.errorBtn(_:)), for: .touchUpInside)
    }

    return cell
}

這是帶有問題的代碼的應用程序快速模型的鏈接。 https://github.com/morenoa/iOS3/tree/master/Table%20Cell非常感謝您的幫助。 抱歉,如果重新發布。 只是難住了。

您的應用似乎沒有辦法知道應返回綠色,因為您僅實現了將其更改為警報/紅色的功能,但您沒有檢查其他任何內容,因此當您在if語句中完成操作時,然后所有的細胞都會改變,因為他們沒有不同的認識。

我希望這有幫助

您可以通過將數組更改為字典並將值設置為true / false來跟蹤按鈕狀態。

例如var myArray = ["my": false, "hello": false]

然后根據鍵的值在cellForRowAt cellForRowAt設置狀態,在func errorBtn(_ sender: UIButton)只需切換所選按鈕的值即可。

首先,您必須保留一個參考,以確保該按鈕已被選中。 其次,最好在cellForRowAt函數上設置按鈕的背景色。

為了保持對所選按鈕的參考,可以以各種方式實現。 通常我使用一個對象數組,該對象在對象上具有bool屬性。

就您而言,我認為最簡單的方法是這樣的,因為您已經有一個用於單元格標題的字符串數組。 您可以創建布爾數組來保持按鈕狀態。 如:

var myArraySelected:[Bool] = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false]

然后在cellForRowAt放置以下代碼以設置按鈕的背景色

if (myArraySelected[indexPath.row]){ cell.fail.backgroundColor = UIColor.red }else{ cell.fail.backgroundColor = UIColor(red: 214.0/255.0, green: 214.0/255.0, blue: 214.0/255.0, alpha: 1.0) }

最后,將errorBtn操作更改為:

@IBAction func errorBtn(_ sender: UIButton) { myArraySelected[(sender as AnyObject).tag] = true self.tableView.reloadData() }

不要忘記為表格視圖創建出口。

暫無
暫無

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

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