swift tableview how to select all rows

人走茶凉 提交于 2020-01-25 05:16:10

问题


I have Button in tableview I want when I press that button will select all cell rows, how to do that? I tried alot but I got nothing

I'm so confused how to make the button contact the cell

I've tried to make var like this

var x = false

then I do like

if( x == true ) { //Code }

and when you press the button it will be true

but I don't know in which func I should put this ? and I don't know how to select all rows

Could someone help me how to Select \ Deselect all rows in cell when pressing button in tableview.

Thank you so much!


回答1:


var selectedUsernameArray : NSMutableArray = []
var username1Array : NSMutableArray = ["hel","dsf","fsdg"]//just a sample

Initially button name should be "Select all"

Button action :

 @IBAction func buttonAction(sender: UIButton) {

   if(sender.titleLabel?.text == "Select all")
    {
        selectedUsernameArray .addObjectsFromArray(username1Array as [AnyObject])
        sender.titleLabel?.text = "Deselect all"
    }
    else
   {
    selectedUsernameArray .removeAllObjects();
    sender.titleLabel?.text = "Select all"
    }

    self.tableView .reloadData()
}

tableview delegate

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    var ob: AnyObject = username1Array .objectAtIndex(indexPath.row);
    cell.textLabel?.text = ob as? String;
    if(selectedUsernameArray .containsObject(ob))
    {
      cell.backgroundColor = UIColor.blueColor();
    }
    else
    {
        cell.backgroundColor = UIColor.whiteColor();
    }
    return cell
}



回答2:


var isSelectAll = false; //global variable

isSelectAll = true;//on button action
self.tableView.reloadData()//on button action

in cellForRowAtIndexPath method

if(isSelectAll==true)
{
cell.backgroundColor = UIColor.blueColor();
}
else
{
cell.backgroundColor = UIColor.white();
}



回答3:


In cellForRowAtIndexPath:

UITableViewCell *cell...

cell.accesoryType = isSelectAll ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;


来源:https://stackoverflow.com/questions/32045424/swift-tableview-how-to-select-all-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!