iOS layoutMargins 的坑:一个活久见的 bug

神奇的效果


有天一回到座位上,张皇失措的应届生同事就好像看到救星一样把我抓过去:“仓薯,不好了,你看它这样了!!”


我一看,从不说粗口的仓薯也忍不住说了一句:“我……去,我做了这么多年 iOS 还从来没遇见这样的事。” 把领导也叫过来看。领导拿来玩了一会儿,然后说:“哈哈哈,感觉真想要实现这个效果,还不是那么容易呢……”



在这里我还是要推荐下我自己建的iOS开发学习群:680565220,群里都是学ios开发的,如果你正在学习ios ,小编欢迎你加入,今天分享的这个案例已经上传到群文件,大家都是软件开发党,不定期分享干货(只有iOS软件开发相关的),包括我自己整理的一份2018最新的iOS进阶资料和高级开发教程

究竟是什么 bug 让我们都这么不淡定呢?看下面的 gif 就知道了:


这个方块形的 cell 就是一个平凡而普通的 collectionView 上平凡而普通的 collectionViewCell,很多地方都在用,用了一年多了,一直都长这个样子,从没出任何问题。然而被我们的应届生同事不知道怎么一改,出现了这样的效果:当 cell 滚动到屏幕边缘,即将离开屏幕的时候,它好像舍不得离开一样,竟然把自己缩起来了……


要不要来帮我 debug


以下是能重现 bug 的代码,能在 iPhone 7 iOS 11 模拟器上重现。为了只写一个文件,我就把代码最简化了,只要 60 行:



import UIKit


final class TestCell: UICollectionViewCell {


  override init(frame: CGRect) {

    let imageView = UIImageView(frame: .zero)

    let metadataView = UIView(frame: .zero)


    super.init(frame: frame)


    imageView.backgroundColor = UIColor.red

    metadataView.backgroundColor = UIColor.green


    for view in [imageView, metadataView] {

      addSubview(view)

      view.translatesAutoresizingMaskIntoConstraints = false

      view.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true

      view.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor).isActive = true

    }


    imageView.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor).isActive = true

    imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true


    metadataView.topAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true

    metadataView.heightAnchor.constraint(equalToConstant: 25).isActive = true

    metadataView.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor).isActive = true

  }


  required public init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")

  }

}


final class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {


  override func viewDidLoad() {

    super.viewDidLoad()


    self.collectionView!.contentInsetAdjustmentBehavior = .never

    self.collectionView!.register(TestCell.self, forCellWithReuseIdentifier: "Cell")

  }


  // MARK: UICollectionViewDataSource


  override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return 10

  }


  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    return collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

  }


  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let measurementCell = TestCell()

    let width = (collectionView.bounds.size.width - 20) / 2.0

    measurementCell.widthAnchor.constraint(equalToConstant: width).isActive = true

    return CGSize(width: width, height: measurementCell.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height)

  }

import UIKit


final class TestCell: UICollectionViewCell {


  override init(frame: CGRect) {

    let imageView = UIImageView(frame: .zero)

    let metadataView = UIView(frame: .zero)


    super.init(frame: frame)


    imageView.backgroundColor = UIColor.red

    metadataView.backgroundColor = UIColor.green


    for view in [imageView, metadataView] {

      addSubview(view)

      view.translatesAutoresizingMaskIntoConstraints = false

      view.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true

      view.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor).isActive = true

    }


    imageView.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor).isActive = true

    imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true


    metadataView.topAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true

    metadataView.heightAnchor.constraint(equalToConstant: 25).isActive = true

    metadataView.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor).isActive = true

  }


  required public init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")

  }

}


final class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {


  override func viewDidLoad() {

    super.viewDidLoad()


    self.collectionView!.contentInsetAdjustmentBehavior = .never

    self.collectionView!.register(TestCell.self, forCellWithReuseIdentifier: "Cell")

  }


  // MARK: UICollectionViewDataSource


  override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return 10

  }


  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    return collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

  }


  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let measurementCell = TestCell()

    let width = (collectionView.bounds.size.width - 20) / 2.0

    measurementCell.widthAnchor.constraint(equalToConstant: width).isActive = true

    return CGSize(width: width, height: measurementCell.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height)

  }


约束用的是系统原生的写法,可能大家平时用第三方库用得多,原生写法反而不熟悉了。简单解释下,假设红色是图片,绿色是描述吧:


  1. 图片左边、右边、上面约束到父 view,高度 = 宽度

  2. 描述左边、右边、下面约束到父 view,高度固定 25,顶部贴着图片底部


代码出来了,能看出是什么问题吗?


几个猜测


Q:是不是 layout 出什么问题了!

A:用的是最简单的 UICollectionViewFlowLayout 啊…… 没 override 任何东西。


Q:是不是 constraint 冲突?

A:你看我约束得有啥问题?明明不会有任何冲突耶。


Q:Cell size 算得不对吧?

A:最普通的自动计算…… 打 log 来看算得是对的。而且,就算是出了问题,滚动的时候也不会实时计算 size 啊…… 它可是一边滚一边缩啊……


Q:view.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true 这个self.layoutMarginsGuide.leadingAnchor是什么鬼,你就不能用self.leadingAnchor吗?

A:你猜对了…… 因为想省事改 self.layoutMargins 所以约束到 layoutMarginsGuide,但确实如果改成约束到普通的self.leadingAnchor就不会有问题了。


Q:这货是不是只有什么特定情况才有的 bug,比如 iOS 11 或者 iPhoneX

A:没错是 iOS 11 才有……任何手机都可以重现,但确实跟 iPhoneX 有点关系……


这下聪明的读者猜出是什么问题了吗?:)


其实就是少了一行


要解决这个问题很简单,就是在 cell 的init方法里加一句


self.insetsLayoutMarginsFromSafeArea = false


insetsLayoutMarginsFromSafeArea 这个属性对于所有UIView默认为YES(我觉得这点并不是太科学),当它为YES的时候,view 的 layoutMargins 会根据 safeArea 进行调整。这样的话,即使把 layoutMargins 设置为一个固定值比如 layoutMargins = .zero,但是到了屏幕边缘的时候,它的 margins 还是会逐渐变大,本意应该是为了让子 view 自动避开 iPhoneX 的刘海吧。这样,出现上面这个效果神奇的 bug也不足为怪了。


Layout Margins 的好处和坑


这么说的话,其实应该是个很常见的问题,为啥平常遇到的不多呢?我想还是因为我们约束到 layoutMarginsGuide 的情况比较少吧。


layoutMargins 这套东西用来改 insets 是非常方便的。比如我写一个用途很广泛的东西,希望能支持使用者随意改动它的 insets,如果我不用 layoutMargins 的话,我需要维护 4 个 constraints:


// properties

var leadingInsetConstraint: NSLayoutConstraint!

var trailingInsetConstraint: NSLayoutConstraint!

var topConstraint: NSLayoutConstraint!

var bottomConstraint: NSLayoutConstraint!


// during init

self.leadingInsetConstraint = someView.leadingAnchor.constraint(equalTo: self.leadingAnchor)

self.leadingInsetConstraint.isActive = true

self.trailingInsetConstraint = someView.trailingAnchor.constraint(equalTo: self.trailingAnchor)

self.trailingInsetConstraint.isActive = true

self.topInsetConstraint = someView.topAnchor.constraint(equalTo: self.topAnchor)

self.topInsetConstraint.isActive = true

self.bottomInsetConstraint = someView.bottomAnchor.constraint(equalTo: self.bottomAnchor)

self.bottomInsetConstraint.isActive = true


// configuration

self.leadingInsetConstraint.constant = inset.left // 假设我们不考虑阿拉伯语吧

self.trailingInsetConstraint.constant = inset.right

self.topInsetConstraint.constant = inset.top

self.bottomInsetConstraint.constant = inset.bottom


而如果我用layoutMagins这套东西,上面这些代码就可以简化很多了,一个属性都不用存:


// during init

self.leadingInsetConstraint = someView.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor)

self.trailingInsetConstraint = someView.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor)

self.topInsetConstraint = someView.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor)

self.bottomInsetConstraint = someView.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor)


// configuration

self.layoutMargins = insets


如果使用 directionalLayoutMargins,连阿拉伯语的情况都自动处理好了。


但它也有一些坑,上面提到的就是其中之一。另外的我随便列两个:


  1. layoutMargins 的默认值居然不是 0。这一点让我永远都不能理解苹果的脑回路,它的默认值是 UIEdgeInsets(8,8,8,8)。也许 8 是某个苹果工程师的幸运数字吧……

  2. 没有加进 view hierarchy 之前,布局可能无法正确使用 layout margins。这一点就比较诡异,印象中以前就遇到需要先 addSubview 再设 layoutMargins,反过来就跟没设一样的神奇 bug,也不知道最新版的系统修好了没有了……


import UIKit


final class TestCell: UICollectionViewCell {


  override init(frame: CGRect) {

    let imageView = UIImageView(frame: .zero)

    let metadataView = UIView(frame: .zero)


    super.init(frame: frame)


    imageView.backgroundColor = UIColor.red

    metadataView.backgroundColor = UIColor.green


    for view in [imageView, metadataView] {

      addSubview(view)

      view.translatesAutoresizingMaskIntoConstraints = false

      view.leadingAnchor.constraint(equalTo: self.layoutMarginsGuide.leadingAnchor).isActive = true

      view.trailingAnchor.constraint(equalTo: self.layoutMarginsGuide.trailingAnchor).isActive = true

    }


    imageView.topAnchor.constraint(equalTo: self.layoutMarginsGuide.topAnchor).isActive = true

    imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true


    metadataView.topAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true

    metadataView.heightAnchor.constraint(equalToConstant: 25).isActive = true

    metadataView.bottomAnchor.constraint(equalTo: self.layoutMarginsGuide.bottomAnchor).isActive = true

  }


  required public init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")

  }

}


final class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {


  override func viewDidLoad() {

    super.viewDidLoad()


    self.collectionView!.contentInsetAdjustmentBehavior = .never

    self.collectionView!.register(TestCell.self, forCellWithReuseIdentifier: "Cell")

  }


  // MARK: UICollectionViewDataSource


  override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return 10

  }


  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    return collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

  }


  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let measurementCell = TestCell()

    let width = (collectionView.bounds.size.width - 20) / 2.0

    measurementCell.widthAnchor.constraint(equalToConstant: width).isActive = true

    return CGSize(width: width, height: measurementCell.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height)

  }

猜你喜欢

转载自blog.csdn.net/qq_41597941/article/details/79688620
今日推荐