2017-07-17 159 views
0

我有一個應用程序,如測驗應用程序。在tableViewCell中,有4個按鈕用於任務的變體。當用戶按下按鈕時,我需要改變顏色,當我嘗試在按鈕的操作中更改顏色時,按鈕顏色在所有表格視圖單元格中發生變化。但我只需要在那個地方改變我在哪裏按下。我已經試着寫的委託,但它給了相同的結果,這是代碼,我怎麼寫我委託:如何更改特定TableViewCell中的按鈕顏色

class CustomButton: UIButton { 

override var isHighlighted: Bool { 
    didSet { 
     if isHighlighted { 
      backgroundColor = UIColor.lightGray 
     } else { 
      backgroundColor = UIColor.init(red: 34/255, green: 89/255, blue: 128/255, alpha: 1.0) 
     } 
    } 
} 

}

我已經添加的目標的行動按鈕。

var variant1 = UIButton() 
var variant2 = UIButton() 
var variant3 = UIButton() 
var variant4 = UIButton() 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "finalCell")! 
    variant1 = cell.contentView.viewWithTag(1) as! UIButton 
    variant2 = cell.contentView.viewWithTag(2) as! UIButton 
    variant3 = cell.contentView.viewWithTag(3) as! UIButton 
    variant4 = cell.contentView.viewWithTag(4) as! UIButton 


    if (numberOfVariants.count != 0) { 
     let questionTextView = cell.contentView.viewWithTag(5) as! UITextView 
     questionTextView.text = "\(Questions[indexPath.row].content!)" 
     variant1.addTarget(self, action: #selector(self.variant1ButtonPressed), for: .touchUpInside) 
     variant2.addTarget(self, action: #selector(self.variant2ButtonPressed), for: .touchUpInside) 
     variant3.addTarget(self, action: #selector(self.variant3ButtonPressed), for: .touchUpInside) 
     variant4.addTarget(self, action: #selector(self.variant4ButtonPressed), for: .touchUpInside) 
      } 
     return cell 
    } 

我已經確定表視圖的indexPath(如果它是有幫助的),當用戶點擊到按鍵:

func variant1ButtonPressed(_ sender:AnyObject) { 
    print("Variant1") 
    let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView) 
    let indexPath = self.tableView.indexPathForRow(at: buttonPosition) 
    let intIndexpath = Int((indexPath?.row)!) 
    globalIndexPath = intIndexpath 
} 
func variant2ButtonPressed(_ sender:AnyObject) { 
    let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView) 
    let indexPath = self.tableView.indexPathForRow(at: buttonPosition) 
    let intIndexpath = Int((indexPath?.row)!) 
    globalIndexPath = intIndexpath 

} 
func variant3ButtonPressed(_ sender:AnyObject) { 
    let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView) 
    let indexPath = self.tableView.indexPathForRow(at: buttonPosition) 
    let intIndexpath = Int((indexPath?.row)!) 
    globalIndexPath = intIndexpath 


} 
func variant4ButtonPressed(_ sender:AnyObject) { 
    let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView) 
    let indexPath = self.tableView.indexPathForRow(at: buttonPosition) 
    let intIndexpath = Int((indexPath?.row)!) 
    globalIndexPath = intIndexpath 


} 

這怎麼它看起來像故事板(如果它是有幫助的) enter image description here

+0

你需要改變顏色,而按鈕觸摸或更改選擇的顏色? –

+0

@ReinierMelian當用戶選擇一個按鈕改變這個按鈕的顏色。 –

+0

您需要實現isSelected而不是isHighlighted屬性才能顯示選定的顏色。 – Surjeet

回答

1

我認爲你正在使用更多的代碼比你真的需要做這個任務,所以這是另一種方法使用closures,我只有一個viewController在我的故事板,並添加一個UITableView裏面和一個叫做ButtonTableViewCell的customCell,然後我把一個普通的UIButton作爲@IBOutlet就是這樣,完整的實施在這裏

https://github.com/rmelian2014/SOButtonsTableViewCellQuestion

EDITED

ButtonTableViewCell

import UIKit 

@IBDesignable 
class ButtonTableViewCell: UITableViewCell { 

    @IBInspectable var selectedColor : UIColor = UIColor.red 
    @IBInspectable var normalColor : UIColor = UIColor.blue 

    static let cellHeigth : CGFloat = 360 

    @IBOutlet var buttonsArray: [UIButton]! 
    var selectedText : String?{ 
     willSet{ 
      guard newValue != nil else{ 
       return 
      } 

      var foundedIndex = -1 
      for (index,text) in self.texts.enumerated() { 
       if(text == newValue!){ 
        foundedIndex = index 
        break 
       } 
      } 

      guard foundedIndex != -1 else 
      { 
       return 
      } 

      self.buttonsArray[foundedIndex].backgroundColor = selectedColor 
     } 
    } 
    var texts : [String] = [] 

    var buttonActionClosure : ((_ selectedText:String?)->Void)? 

    func setupWithClosure(texts:[String],textSelected:String?,closure:((_ selectedText:String?)->Void)?) 
    { 
     self.texts = texts 

     for (index,button) in self.buttonsArray.enumerated(){ 
      if(self.texts.count > index) 
      { 
       button.setTitle(self.texts[index], for: .normal) 
      } 
      button.tag = index 
      button.backgroundColor = self.normalColor 
     } 


     self.selectedText = textSelected 
     if(closure != nil) 
     { 
      self.buttonActionClosure = closure 
     } 


    } 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 
    } 

    override func setSelected(_ selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 

     // Configure the view for the selected state 
    } 

    @IBAction func buttonAction(sender:UIButton) 
    { 
     if(self.texts.count > sender.tag){ 
      let newSelectedText = self.texts[sender.tag] 

      if(newSelectedText != self.selectedText){ 
       self.selectedText = newSelectedText 
      }else 
      { 
       self.selectedText = nil 
      } 
     } 
     if(self.buttonActionClosure != nil) 
     { 
      self.buttonActionClosure!(self.selectedText) 
     } 
    } 

    override func prepareForReuse() { 
     super.prepareForReuse() 
     self.buttonActionClosure = nil 
    } 

} 

的ViewController

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var tableView: UITableView! 

    var dictOfSelectedsCells : [Int:String?] = [:] 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     tableView.delegate = self 
     tableView.dataSource = self 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


} 

extension ViewController : UITableViewDelegate,UITableViewDataSource 
{ 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 4 
    } 

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     return ButtonTableViewCell.cellHeigth 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     if let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonTableViewCell", for: indexPath) as? ButtonTableViewCell 
     { 
      cell.selectionStyle = .none 
      var selectedText : String? 
      if let currentSelectedText = self.dictOfSelectedsCells[indexPath.row] 
      { 
       selectedText = currentSelectedText 
      } 

      cell.setupWithClosure(texts:["Variant1","Variant2","Variant3","Variant4"], textSelected: selectedText, closure: { [weak self] (selected) in 
       debugPrint(indexPath) 
       self?.dictOfSelectedsCells[indexPath.row] = selected 
       tableView.reloadRows(at: [indexPath], with: .none) 
      }) 

      return cell 
     } 
     assert(false, "this must not happen") 
    } 
} 

希望這有助於你

+0

我必須連接到ButtonTableViewCell所有4個按鈕? –

+0

@АзаматБулегенов不,你只需要在你的故事板來定義你的customCell,我可以發表圖片,如果你想 –

+0

這是工作,我試圖謝謝你幫助你的。但是,您可以編輯代碼,以4個按鈕 –

0

在你cellForRowAt indexPath:方法,你需要檢查,如果該行的indexpath是一樣的選擇按鈕的indexpath。如果相同,則需要顯示高亮顏色,否則顯示正常顏色。

這樣保存了buttonpressed方法中全局變量中按下的按鈕的indexpath。讓valiable被選中按鈕指數路徑。

添加下面的代碼在你的cellForRowAt indexPath:方法

if indexPath.row==selectedButtonIndexPath.row { 
     backgroundColor = UIColor.lightGray 
    } else { 
     backgroundColor = UIColor.init(red: 34/255, green: 89/255, blue: 128/255, alpha: 1.0) 
    } 

而且ofcourse刷新你的tableview當點擊一個按鈕,以反映顏色的變化。

更新1:

你可以嘗試讓sender.tag保存按鈕的標籤,以及在你按下按鈕的方法,然後改變你的,如果條件

if indexPath.row==selectedButtonIndexPath.row { 
    if buttonTag == 1{ 
     variant1.backgroundcolor = UIColor.lightGray 
     variant2.backgroundColor = UIColor.init(red: 34/255, green: 89/255, blue: 128/255, alpha: 1.0) 
     // and so on for all buttons. 
    }else if buttonTag == 2{ 
     // same as above but for variant2 
    } 
} else { 

} 
+0

我創建了全局變量selectedButtonIndexPath並將其等同於選定的按鈕索引路徑,並將您寫入的函數添加到cellForRowAt函數中,該函數不工作。 –

+0

你現在可以更新你的代碼嗎 –

+0

完成!!!!!!!!!更改了代碼 –