【问题标题】:swift tableview how to select all rowsswift tableview如何选择所有行
【发布时间】:2015-11-09 19:07:50
【问题描述】:

我在 tableview 中有我想要的按钮,当我按下该按钮将选择所有单元格行时,该怎么做?我尝试了很多,但没有得到任何结果

我很困惑如何让按钮与单元格联系

我尝试过制作这样的 var

var x = false

那我喜欢

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

当你按下按钮时它会是真的

但我不知道我应该把它放在哪个函数中?而且我不知道如何选择所有行

有人可以帮我在表格视图中按下按钮时如何选择\取消选择单元格中的所有行。

非常感谢!

【问题讨论】:

  • 如果没有全选功能,有没有办法在我按下按钮时更改所有行的背景颜色?
  • 整个视图的背景颜色?
  • 单元格行的背景,使用其他 swift 文件的单元格和使用另一个 swift 文件的表格视图 表格视图中的按钮
  • 在按钮动作上设置一个布尔值,重新加载tableView。因此 cellForRowAtIndexPath 方法将调用,在此方法中,您使用 bool 值检查条件并设置 cell.backgroundColor = UIColor.blueColor();

标签: swift uitableview button


【解决方案1】:
var selectedUsernameArray : NSMutableArray = []
var username1Array : NSMutableArray = ["hel","dsf","fsdg"]//just a sample

最初按钮名称应为“全选”

按钮操作:

 @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 委托

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
    

    cellForRowAtIndexPath方法中

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

    【讨论】:

    • 谢谢,我试过了,但行背景仍然是白色的,不会改变!
    • 我做了,我发现了问题,请看一下,当我按下按钮而不是更改颜色时,我怎样才能只选择所有行?
    • 你能告诉我如何将包含数组添加到其他数组吗?
    • selectedUsernameArray .addObjectsFromArray(username1Array as [AnyObject])
    【解决方案3】:

    在 cellForRowAtIndexPath 中:

    UITableViewCell *cell...
    
    cell.accesoryType = isSelectAll ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
    

    【讨论】:

    • 谢谢,那代码是什么?当我按下按钮时,你能帮我选择所有行吗?
    • 当用户点击按钮时调用[tableView reloadData],cellForRowAtIndexPath:会被自动调用。
    • 你能告诉我如何将包含数组添加到其他数组吗?
    • NSArray *newArray = [NSArray arrayWithArray:otherArray];
    • 我正在使用 swift 不是 Objective-c,或者我如何获取行中的所有用户名并将它们添加到数组中?当我按下按钮时!
    猜你喜欢
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    相关资源
    最近更新 更多