首页 文章

无法在UNNotificationContentExtension上使用AutoLayout约束

提问于
浏览
2

我正在尝试在iOS 10中添加一个自定义通知,该通知使用强制按下丰富的通知 . 我想以编程方式将视图添加到视图控制器的中心,该视图继承自UNNotificationContentExtension,但我得到的只是一个白色屏幕 . 当我给它一个这样的帧时添加内容:

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) {

    }

}

看起来像这样:
enter image description here
但是当我尝试使用此代码以编程方式(使用PureLayout包装器)使用AutoLayout时:

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) {

    }

}

结果如下:
enter image description here

什么会导致AutoLayout无法在此视图控制器中工作?我也用界面构建器测试了它,所以我很困惑 .

1 回答

  • 0

    以编程方式创建视图时,必须记住将 translatesAutoresizingMaskIntoConstraints 设置为false,否则自动布局将不会像您期望的那样运行 .

相关问题