单元格上的自定义tableview滚动问题

时间:2015-05-30 09:27:57

标签: ios uitableview swift scroll tableviewcell

我有一个以编程方式创建的tableview

var tableView: UITableView  =   UITableView()
var items = ["1","2","3","4","5","6"," 1","L 2","La 3","La 4","La 5","La 6","L 7","La 8","La 9","La 10","La 11","Lab 12","Lab 13","Lab 14","Lab 15","Lab 16","Lab 17","Lab 18","Lab 19","Lab 20","La 1","L 2","La 3"]

   override func viewDidLoad() {
    super.viewDidLoad()
    tableView.frame         = CGRectMake(0, 50, self.view.frame.width,100);  //If we give self.view.frame.height It worked because no need to scroll
    tableView.delegate      = self
    tableView.dataSource  =  self
    tableView.estimatedRowHeight = 30
   tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    self.view.addSubview(tableView)
    }

以下是有问题的代码

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
        if indexPath.row == 2 || indexPath.row == 3 {
            var redBtn = UIButton()
            redBtn = UIButton(frame: CGRectMake(0, 0, 40, 40))
            redBtn.backgroundColor = UIColor.redColor()
            redBtn.setTitle("das", forState: UIControlState.Normal)         
            cell.contentView.addSubview(redBtn)
        }else {
        cell.textLabel?.textAlignment = NSTextAlignment.Center
        cell.textLabel?.text = items[indexPath.row]
       }
       return cell
   }
}

在第2行和第3行只有我需要显示按钮。但是当滚动tableview时它会显示在所有单元格中。如果将tableview高度增加到查看高度,那么没有问题,因为没有滚动发生。< / p>

我从这里读到了这个问题UITableView scrolling and redraw issue我发现这是因为在滚动时重用单元格问题。但是这个解决方案对我来说不起作用。

欢迎使用合适的解决方案。我提供了完整的代码,您可以将其复制并粘贴到项目中,并解决问题。

感谢提前

1 个答案:

答案 0 :(得分:2)

当您重复使用单元格时,旧值仍然存在,因此每次使用dequeueReusableCellWithIdentifier时,您都需要重置为默认值或仍在其中缓存的最后值。在您的特定情况下,您需要删除从单元格创建的按钮或将其设置为隐藏在else语句中。

From apple documentation:

  

表视图的数据源实现   tableView:cellForRowAtIndexPath:应始终重置所有内容   重用一个单元格。

实现此目的的最佳方法是在您根据需要创建一个包含所有组件的自定义单元格(按钮,标签等),然后根据需要将隐藏属性隐藏的新自定义单元格设置为true或false。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! MyCustomCell
        if indexPath.row == 2 || indexPath.row == 3 {
            redBtn.hidden = false
            cell.contentView.addSubview(redBtn)
        }else {
            redBtn.hidden = true
            cell.textLabel?.textAlignment = NSTextAlignment.Center
            cell.textLabel?.text = items[indexPath.row]
      }
      return cell

在这种情况下,以编程方式动态创建按钮并不是一个好主意,因为您必须循环每个可重用单元格的单元格中的所有子视图,以确定它是否已存在以决定是否需要创建或删除,如下所示:

for button:AnyObject in subviews{
    if(button .isKindOfClass(UIButton)){
       if(button.accessibilityIdentifier == "MyButton"){
            println("Button Already Exists")
        }else{
            println("Create new button")
        }
    }
}

我希望能帮到你