Swift default AlertViewController breaking constraints

前端 未结 9 657
野趣味
野趣味 2020-11-27 14:25

I am trying to use a default AlertViewController with style .actionSheet. For some reason, the alert causes a constraint error. As long as

相关标签:
9条回答
  • 2020-11-27 15:14

    If you want to keep animation and all constraints, you should find a negative constraint and make it positive before presenting alert controller.

    // Find negative constraint and make it positive
    for subview in alert.view.subviews {
        for constraint in subview.constraints {
            if constraint.constant < 0 {
                constraint.constant = -constraint.constant
            }
        }
    }
    
    // Present alert controller
    present(alert, animated: true)
    
    0 讨论(0)
  • 2020-11-27 15:15

    This error is not critical, seems to be unfixed bug form Apple. This constraint appears in animation style just after presenting. I tried to catch and change it (change values, relations, priority) before presenting – no success because of this dynamically added constraints.

    When you turn off animation in self.present(alert, animated: false) and using alert.view.addSubview(UIView()) – the error disappears. I can't explain it, but it works!

    let alert = UIAlertController(title: "Change your profile image", message: nil, preferredStyle: .actionSheet)
    
    alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: nil))
    alert.addAction(UIAlertAction(title: "Online Stock Library", style: .default, handler: nil))
    let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
    
    alert.addAction(cancel)
    alert.view.addSubview(UIView()) // I can't explain it, but it works!
    
    self.present(alert, animated: false)
    
    0 讨论(0)
  • 2020-11-27 15:15

    Adding to this answer...This seems to remove the issue for me and doesn't require any changes to existing code.

    extension UIAlertController {
        override open func viewDidLoad() {
            super.viewDidLoad()
            pruneNegativeWidthConstraints()
        }
    
        func pruneNegativeWidthConstraints() {
            for subView in self.view.subviews {
                for constraint in subView.constraints where constraint.debugDescription.contains("width == - 16") {
                    subView.removeConstraint(constraint)
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题