iOS 11 safe area layout guide backwards compatibility

前端 未结 16 1126
忘了有多久
忘了有多久 2020-12-02 05:42

Is enabling Safe Area Layout Guides compatible to iOS below 11?

16条回答
  •  一整个雨季
    2020-12-02 06:14

    I found a more convenient way where you only need to subclass the NSLayoutConstraintthat is pinned to your safeArea.

    It's kinda hacky since you have to get the ViewController from a UIView but in my opinion, that's an easy and good alternative until Apple finally fixes backward compatibility for the safeArea in Xibs.

    Subclass:

    class SafeAreaBackwardsCompatabilityConstraint: NSLayoutConstraint {
    private weak var newConstraint: NSLayoutConstraint?
    
    override var secondItem: AnyObject? {
        get {
            if #available(iOS 11.0, *) {}
            else {
                if let vc = (super.secondItem as? UIView)?.parentViewController, newConstraint == nil {
                    newConstraint = (self.firstItem as? UIView)?.topAnchor.constraint(equalTo: vc.topLayoutGuide.bottomAnchor)
                    newConstraint?.isActive = true
                    newConstraint?.constant = self.constant
                }
            }
            return super.secondItem
        }
    }
    
    override var priority: UILayoutPriority {
        get {
            if #available(iOS 11.0, *) { return super.priority }
            else { return 750 }
        }
        set { super.priority = newValue }
    }
    }
    
    private extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
    }
    

    Xib:

提交回复
热议问题