Swift:使用自定义accessoryType进行单元冻结UI和99%CPU使用率

时间:2016-03-11 03:48:26

标签: ios xcode swift uitableview

我正在尝试为我的tableview单元使用自定义附件类型(UIImage),它具有展开/折叠功能。当用户点击一个单元格时,如果再次点击父级,则该行会展开或拼写。

我用来设置配件类型的imageview如下:

var expandIcon : UIImageView?
expandIcon  = UIImageView(frame:CGRectMake(0, 0, 16, 16))
expandIcon!.image = UIImage(named:"expand")

以下代码是当用户点击一行时,如果其父级应该是epxand,或者如果它已经展开,则会崩溃。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellData = dataForCellAtRowIndex[indexPath.section]!.rows[indexPath.row]
    var cell:UITableViewCell!

    if isParentCell(indexPath.row) == true {
        cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)            
        cell.textLabel?.text = "test" + String(indexPath.row)
        cell.detailTextLabel?.text = "detail"
        cell.backgroundColor = UIColor.whiteColor()
        cell.accessoryView = expandIcon

    }else{
        cell = tableView.dequeueReusableCellWithIdentifier("childCell", forIndexPath: indexPath)
        cell.backgroundColor = UIColor.lightGrayColor()
        cell.textLabel?.text = "child name"
        cell.detailTextLabel?.text = "child detail"
        cell.accessoryType = UITableViewCellAccessoryType.None
    }

    return cell
}

引起问题的位是cell.accessoryView = expandAccessory,这导致UI冻结,并且xpu报告的cpu使用率达到99%。如果我删除cell.accessoryView = expandIcon一切都很好!为什么会这样?

2 个答案:

答案 0 :(得分:3)

您应该实现一个函数来返回一个expandIcon,然后调用它来代替expandIcon变量。

func expandImageView() -> UIImageView {
    let expandIcon  = UIImageView(frame:CGRectMake(0, 0, 16, 16))
    expandIcon.image = UIImage(named:"expand")
    return expandIcon
}

cell.accessoryView = expandImageView()

答案 1 :(得分:0)

@rmaddy提到的解决方法是重用UIImage视图导致UI冻结。为每个单元格创建一个新的UIImage解决了我的问题,而不是:

if isParentCell(indexPath.row) == true {
    cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)            
    cell.textLabel?.text = "test" + String(indexPath.row)
    cell.detailTextLabel?.text = "detail"
    cell.backgroundColor = UIColor.whiteColor()
    cell.accessoryView = expandIcon

}

我必须:

if isParentCell(indexPath.row) == true {
    cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)            
    cell.textLabel?.text = "test" + String(indexPath.row)
    cell.detailTextLabel?.text = "detail"
    cell.backgroundColor = UIColor.whiteColor()

    //put the below two lines in a func and return a UIImage 
    let expandIcon  = UIImageView(frame:CGRectMake(0, 0, 16, 16))
    expandIcon.image = UIImage(named:"expand")

    cell.accessoryView = expandIcon

}