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

神奇的效果

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

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

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

shrink_bad_demo.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)
  }
}

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

  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,也不知道最新版的系统修好了没有了……
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 用到的组件 1、通过CocoaPods安装 2、第三方类库安装 3、第三方服务 友盟社会化分享组件 友盟用户反馈 ...
    SunnyLeong阅读 14,500评论 1 180
  • 回单位,拼车。后排是一起的三个20以内的小男孩。现在的孩子都是这样,长腿,瘦脸,比我们那时候漂亮多了。 BUT!之...
    简书2017阅读 364评论 0 0
  • 第二天一早林雪在闹钟响第三遍时才醒,觉得头昏昏沉沉的,身体僵硬仿佛没休息似的。 她叹着气起床,准备好早饭再把团团从...
    张氏春红阅读 252评论 0 0
  • 今天和朋友一起,为了组织孩子们的插画展,去和有关工作人员协商,以及前期探路等等。 因为在洽谈的过程中有些频率不对,...
    源源哒阅读 166评论 0 0