how to change the button title on click inside a tableview cell in swift 3

前端 未结 3 594
野趣味
野趣味 2021-01-01 06:28

I got a tableview cell inside that i have image view , label and a ui button , i need to change the button title text and background colour on click . But when i try to do

3条回答
  •  萌比男神i
    2021-01-01 06:59

    First of all you should take one Array for manage clicked/changed UIButton for reusableCell otherwise if you scroll your tableView Up-Down then It will be remove effect

    I'm giving my logic.

    1) Take one mutable Array name is temArray (Size equal to your tableView's Row) and it has 0 value for each index. you can do it by easy repeat value 0.

    2) in you cellForRowAtIndexPath datasource method check

    if temArray[indexPath.row] == 0 {
       /// Write code for default UIButton - That has normal behavior means not changed title and no set background color
    }
    else {
      /// Write code for What you want to keep UIButton title and background color
    }
    
    cell.yourButtonObject.tag = indexPath.row
    cell.yourButtonObject.addTarget(self, action:#selector(handleButtonClicked(_:)), for: .touchUpInside). 
    

    3) And add handleButtonClicked method and change temArray value

    func handleButtonClicked(_ sender: UIButton) {
            let myIndexPath = NSIndexPath(row: sender.tag, section: 0)
            let cell = tblViewPref.cellForRow(at: myIndexPath as IndexPath)
            if temArray[sender.tag] == 0 {
            /// You can access your button by
            // cell.myButton..... change here text and background color
            // And change "temArray"
    
            temArray[sender.tag] = 1
           }
           else {
    
               /// You can access your button by
              // cell.myButton..... change here text and background color
              // And change "temArray"
    
             // SET DEFULT BUTTON TITLE AND BACKGROUND COLOR
    
             temArray[sender.tag] = 0
           }
        }
    

    So when you scroll your table Up-down temArray will be managed by it's value at indexPath in cellForRowAtIndexPath Datasource method.

提交回复
热议问题