美文网首页
隐藏Stack View里的View时的一个坑

隐藏Stack View里的View时的一个坑

作者: 张宇航_Ken | 来源:发表于2016-08-11 22:54 被阅读1015次

    记录下来希望能帮到其他人。

    Problem

    Stack View

    上图A、B、C 3个View是放在一个Stack View中的。其中A和C都有一个高度为100的constraint。

    当点击C时,会通过设置hidden = true来隐藏C。变成这样:

    Hide C

    B没有constrain,所以自动拉大填充了C的位置。此时没报任何错误。但是一旦旋转屏幕,控制台会打出了以下信息:

    Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
    (
    "<NSLayoutConstraint:0x7f91b1d5fee0 V:[UIView:0x7f91b1d5f750(100)]>",
    "<NSLayoutConstraint:0x7f91b1d6ef80 'UISV-hiding' V:[UIView:0x7f91b1d5f750(0)]>"
    )
    Will attempt to recover by breaking constraint
    <NSLayoutConstraint:0x7f91b1d5fee0 V:[UIView:0x7f91b1d5f750(100)]>
    Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
    The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

    这表示有两个constraint冲突了。

    Debug

    看这个错误信息是不是一头雾水?

    "<NSLayoutConstraint:0x7f91b1d5fee0 V:[UIView:0x7f91b1d5f750(100)]>",
    "<NSLayoutConstraint:0x7f91b1d6ef80 'UISV-hiding' V:[UIView:0x7f91b1d5f750(0)]>"

    首先要知道是哪个View的constraint,所以先给各个View加上Identifier以方便标识。

    多嘴一句。此处的例子比较简单,总共才3个View,猜都能猜出来。但在实际项目中就没那么容易了。所以掌握基本的debug技巧还是很有必要的。

    选中A,找到Identity Inspector面板,再找到Accessibility里面的Identifier,如图:


    Identifier

    相应地设置B和C。再跑一次程序,会发现错误信息变成这样

    "<NSLayoutConstraint:0x7f8f4153ab30 V:[C(100)] (Names: C:0x7f8f4153a3a0 )>",
    "<NSLayoutConstraint:0x7f8f41516b80 'UISV-hiding' V:[C(0)] (Names: C:0x7f8f4153a3a0 )>"

    显然是V:[C(100)]V:[C(0)]冲突了。第一个是我们设置的,第二个是UIStackView发现内部有subview被隐藏时自动添加的。从名字也能看出来:UISV-hiding

    Solution

    V:[C(100)]的优先级调低一点就可以解决了。

    Constraint Priority

    工程戳这里

    One More Thing

    UISV-hiding是什么时候添加进去的?为什么刚隐藏时没报冲突,等到旋转屏幕时才报?
    问得好!这个我也不知道……请路过的同学解答一下吧。

    本文如有错误还请雅正。万分感谢~~

    相关文章

      网友评论

          本文标题:隐藏Stack View里的View时的一个坑

          本文链接:https://www.haomeiwen.com/subject/vmnjsttx.html