菜鸟教程小白 发表于 2022-12-11 18:00:34

ios - 无法在 UNNotificationContentExtension 上使用 AutoLayout 约束


                                            <p><p>我正在尝试在 iOS 10 中添加一个自定义通知,该通知利用强制按下丰富的通知。我想以编程方式将一个 View 添加到从 UNNotificationContentExtension 继承的 ViewController 的中心,但我得到的只是一个白屏。当我给它一个这样的框架时,内容被添加:</p>

<pre><code>import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    override func viewDidLoad() {
      super.viewDidLoad()
      let myView = UIView()
      myView.backgroundColor = UIColor.red
      myView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
      self.view.addSubview(myView)
    }

    func didReceive(_ notification: UNNotification) {

    }

}
</code></pre>

<p>看起来像这样:
<a href="/image/GuHsG.png" rel="noreferrer noopener nofollow"><img src="/image/GuHsG.png" alt="enter image description here"/></a>
但是当我尝试使用以下代码以编程方式(使用 PureLayout 包装器)使用 AutoLayout 时:</p>

<pre><code>import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    override func viewDidLoad() {
      super.viewDidLoad()

      let myView = UIView()
      myView.backgroundColor = UIColor.red
      self.view.addSubview(myView)

      myView.autoPinEdge(toSuperviewEdge: .top)
      myView.autoPinEdge(toSuperviewEdge: .left)
      myView.autoMatch(.width, to: .width, of: self.view)
      myView.autoMatch(.height, to: .height, of: self.view)
    }

    func didReceive(_ notification: UNNotification) {

    }

}
</code></pre>

<p>结果是这样的:<a href="/image/qv8AO.png" rel="noreferrer noopener nofollow"><img src="/image/qv8AO.png" alt="enter image description here"/></a> </p>

<p>什么会导致 AutoLayout 在此 ViewController 中不起作用?我也用界面生成器测试过,所以我很困惑。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>当您以编程方式创建 View 时,您必须记住将 <code>translatesAutoresizingMaskIntoConstraints</code> 设置为 false,否则自动布局将不会像您预期的那样运行。 </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 无法在 UNNotificationContentExtension 上使用 AutoLayout 约束,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40472293/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40472293/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 无法在 UNNotificationContentExtension 上使用 AutoLayout 约束