gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:23:27 24 4
gpt4 key购买 nike

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

这是生成按钮的代码:

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 中的一些技巧增强表格 View 的文章

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

最佳答案

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

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

关于ios - 动态生成按钮时应用程序移动缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34323223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com