【问题标题】:app is moving slow when dynamically generating buttons动态生成按钮时应用程序运行缓慢
【发布时间】:2015-12-16 22:20:43
【问题描述】:

我想为 iOS 构建一个新闻应用程序,其中每篇文章都被分成类别并显示在表格视图中。因此,如果一篇文章有​​ 2 个类别(例如:编码和编程),那么显示这篇文章的单元格也应该有 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 文章中的一些技巧来增强表格视图

知道为什么当我向按钮添加标题时应用程序开始滞后吗?

【问题讨论】:

    标签: ios swift uitableview uibutton


    【解决方案1】:

    如果您在willDisplayCell 中调用此代码,则在重复使用这两个按钮时,您会一次又一次地将它们添加到相同的单元格中,因此在滚动几次之后,每个单元格中就会有数十个按钮。

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

    【讨论】:

    • 谢谢,我这几天一直在做这个。你能告诉我如何在调用 awakeFromNib 之前实例化一个单元格属性吗?基本上我从服务器接收类别,我需要在单元格对象中发送类别数组。再次感谢。
    • 你不需要在 awakeFromNib 之前设置它,那是为了初始化单元格的 UI - 在 ViewController 中将数据与单元格分开,然后设置数据为将在 cellForRowAtIndexPath 函数中显示在该行的单元格中的右行。
    • 如果我这样做,我怎么知道我需要在单元格中添加多少按钮?按钮的数量可能因文章而异,按钮框架取决于标题的长度。
    • 那么至少你应该在添加新按钮之前删除旧按钮。
    【解决方案2】:

    我的问题的解决方案是在 willDisplayCell 中添加按钮并在 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 的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多