动态生成按钮时,应用程序移动缓慢

时间:2015-12-16 22:20:44

标签: ios swift uitableview uibutton

我想为iOS构建一个新闻应用,其中每篇文章都分为几类并显示在表格视图中。因此,如果一篇文章有​​两个类别(例如:编码和编程),那么显示这篇文章的单元格也应该有2个按钮,每个类别一个。如果我添加没有文本的按钮,那么表视图效果很好。但是如果我在按钮上添加一个标题,那么在几次滚动之后应用程序开始滞后。

这是生成按钮的代码:

func createHashtagButtonsWith(var categories categories: Array<JSON>, cell: ExploreTableViewCell)
{

    var x: CGFloat = 0;
    var y: CGFloat = 0;
    for( var i = 0; i < hashtags.count; i++){
        let size = categories[i].stringValue.sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13.0)]);

        if (x + size.width + 16 > cell.categoryView.frame.size.width){
            x = 0;
            y = size.height + 10;
            cell.categoryView.frame.size.height = cell.categoryView.frame.size.height + size.height + 12;
        }

        let categoryButton : UIButton = UIButton(frame: CGRect(x: x, y: y, width: size.width + 16, height: size.height + 8));
       categoryButton.setTitle("\(categories[i].stringValue)", forState: .Normal);
        categoryButton.backgroundColor = UIColor.flatBlueColorDark();
        categoryButton.layer.masksToBounds = true;
        categoryButton.layer.cornerRadius = 3;

        cell.categoryView.addSubview(categoryButton);
        x += size.width + 24;
    }
}

我从tableView willDisplayCell

中调用此方法

此外,我还使用了此perfect smooth scrolling in uitableviews文章中的一些提示来增强表格视图

任何想法为什么当我为按钮添加标题时应用程序开始滞后?

2 个答案:

答案 0 :(得分:1)

如果你在willDisplayCell中调用此代码,则在重复使用这些代码时会反复将这两个按钮添加到相同的单元格中,因此在几次滚动后,每个单元格中都有数十个按钮。

在单元格中创建按钮(在awakeFromNib左右)以避免这种情况。

答案 1 :(得分:0)

我的问题的解决方案是在willDndplayCell中添加按钮并删除didEndDisplayingCell中该单元格的所有按钮。基本上问题是,每次单元格显示时我都会添加按钮,我会有很多按钮堆叠在每个单元格的顶部。

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let tableCell = cell as! ExploreTableViewCell;
    let subviews = tableCell.hashtagsView.subviews;
    // todo: should replace with a for in
    for (var i = 0; i < subviews.count; i++) {
        if(subviews[i].isKindOfClass(UIButton)){
            subviews[i].removeFromSuperview();
        }
    }
}

感谢TheEye的帮助。

相关问题