Как изменить текст метки UITableviewCell после нажатия кнопки UIButton? - PullRequest
0 голосов
/ 22 января 2019

У меня есть флажок (UIButton) и метка в UITableViewCell. Я хочу изменить текст метки (цвет + зачеркнутый), когда нажимаю на флажок.

Это для приложения рецепта. После того, как готовый шаг сделан, пользователь может «проверить», как это сделано.

Это моя текущая функция cellForRowAt для tableView:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == groceryTableView {
        let cell = tableView.dequeueReusableCell(withIdentifier: groceryTableViewCell, for: indexPath) as! GroceryItemTableViewCell
        cell.amoutLabel.text = indexPath.item % 2 == 0 ? "50 g" : "500 ml"
        cell.itemLabel.text = indexPath.item % 2 == 0 ? "Cheese" : "Milk"
        cell.selectionStyle = .none
        return cell
    }
    else {
        let cell = tableView.dequeueReusableCell(withIdentifier: cookingStepTableViewCell, for: indexPath) as! CookingStepTableViewCell
        cell.cookingStepDescription.text = indexPath.item % 2 == 0 ? "Test 123..." : "Test 321..."
        cell.selectionStyle = .none
        cell.delegate = self
        return cell
    }
}

И это моя функция Button addTarget, которая делегирована из класса TableViewCell фактическому классу ViewController:

func cookingStepDone(description: String, isDone: Bool) {
    // if isDone == true
    // label textcolor is gray + strikethrough

    // if isDone == false
    // no change...
}

Я хочу, чтобы метка cell.cookingStepDescription была изменена, если "isDone" имеет значение true (= установите флажок)

Ответы [ 4 ]

0 голосов
/ 23 января 2019

Оформить заказ на этот код: RecipeTableViewCell

class RecipeTableViewCell: UITableViewCell {

@IBOutlet var myButton : UIButton!
@IBOutlet var myLabel : UILabel!

var buttonClick : (() -> Void)? = nil

override func awakeFromNib() {
    myButton.addTarget(self, action: #selector(didTouchButton(sender:)), for: .touchUpInside)
}

@IBAction func didTouchButton(sender : UIButton)
{
    if let action = buttonClick {
        action()
    }
}
}

В cellForRowAt

let cell = tableView.dequeueReusableCell... 
// Your code ...
cell.buttonClick = {
  //access your label and data from here
  cell.yourLbl.text = yourModel[indexPath.row].text
}
0 голосов
/ 22 января 2019

Предполагается, что кнопка выхода берется в ячейке класса. поэтому объявите метод действия в cellForRowAtIndexpath, например, так.

 cell.yourDoneBtn?.addTarget(self, action: #selector(self.cookingStepDone), for: .touchUpInside)

Теперь в вашей функции действия:

@objc func cookingStepDone(sender: UIButton)
 {
    let location = self.yourTableViewName?.convert(sender.bounds.origin, from:sender)
    let indexPath = self.yourTableViewName?.indexPathForRow(at: location!)
    if let cell = self.yourTableViewName.cellForRow(at: indexPath!) as? yourTableViewCell  // i.e groceryTableViewCell or CookingStepTableViewCell
    {
      if isDone == true
      {
        // Set your cell label textcolor to gray + strikethrough 
      }
      else
      {
       // no change
      }
    }
    DispatchQueue.main.async
    {
       self.yourTableView.reloadData() // reload your table view 
    }
 }

Установите значение bool там, где это необходимо.

0 голосов
/ 22 января 2019

Что если вы создадите новый класс, суперкласс которого будет UITableViewCell, и внутри этого класса вы добавите свои @IBOutlets (UIButton и UILabel) и @IBAction (buttonWasTapped)?

Что-то вроде:

class RecipeTableViewCell: UITableViewCell {

    @IBOutlet var myButton : UIButton!
    @IBOutlet var myLabel : UILabel!

    @IBAction func didTouchButton(sender : UIButton)
    {
         myLabel.textColor = UIColor.green;
    }
}
0 голосов
/ 22 января 2019

Вы можете сделать это, используя следующий подход

определить массив, в вашем методе cookingStepDone добавьте indexPath к массиву, а если indexPath уже в массиве, удалите его и перезагрузите tableView.и в методе cellForRowAtIndexpath проверьте, содержит ли массив массив indexPath.если содержит make text strikeThrough, то сделайте normal.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...