Swift UIView内存使用情况并处理许多子视图

时间:2018-09-02 07:10:46

标签: ios swift

我正在制作一个单词搜索应用程序,其中显示了一个14x14的大型字母网格。现在,我使用自己的df <- data.frame( id = c(1:5), trials = c(rep(1, 2), rep(2, 1), rep(3, 2)), t1 = c(NA, 7, NA, 6, NA), t2 = c(NA, NA, 3, 7, 12), t3 = c(NA, NA, NA, 4, NA) ) 显示每个字母,如下所示:

var update = {$inc : { Attendance: 1 }, $set : {
    "LastDateTimeAttended.Year": year, "LastDateTimeAttended.Month": month, "LastDateTimeAttended.Day": day, "LastDateTimeAttended.Hours": hours, "LastDateTimeAttended.Min": min, "LastDateTimeAttended.Sec": sec
  }};

但是,我想知道是否最好像这样构造我的代码:

UILabel

我的理论是,尽管我找不到任何有关每个for _ in 0..<14 { for _ in 0..<14 { let letterLabel = UILabel() letterLabel.text = randomLetter() addSubview(letterLabel) } } 会占用多少内存的文档,但这会减少我的应用程序的内存占用。

但是,我想知道,后一种方法实际上可以为我节省多少内存?哪种方法是iOS开发中的标准/首选方法?还是我没有想到的第三种方法?

从性能的角度来看,我认为后者是更好的方法,但是当要在屏幕上均匀分布字母并确定要点击哪个字母时,会使代码复杂化。

(注意:这个问题大大简化了我的实际代码,以突出显示问题区域)

1 个答案:

答案 0 :(得分:0)

由于您想知道哪个字母被点击,因此建议您使用集合视图。这是一个示例实现:

private let reuseIdentifier = "Cell"

class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    //Here I am generating an array of 14*14 strings since I don't have access to the randomLetter() function
    let elements = (0..<(14 * 14)).map { String($0) }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.register(CollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return elements.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
        cell.label = UILabel(frame: cell.bounds)
        cell.label.text = elements[indexPath.row] //In your case you would use: cell.label.text = randomLetter()
        cell.label.font = UIFont(name: "helvetica", size: 10)
        cell.label.textAlignment = .center
        cell.addSubview(cell.label)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let size = CGSize(width: self.view.frame.size.width/14, height: self.view.frame.size.width/14)
        return size
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
        print(String(describing: cell.label.text))
    }
}

CollectionViewCell是自定义UICollectionViewCell的地方,定义如下:

class CollectionViewCell: UICollectionViewCell {
    var label: UILabel!
}