OGeek|极客世界-中国程序员成长平台

标题: ios - 无法在 UNNotificationContentExtension 上使用 AutoLayout 约束 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:00
标题: ios - 无法在 UNNotificationContentExtension 上使用 AutoLayout 约束

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

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 在此 View Controller 中不起作用?我也用界面生成器测试过,所以我很困惑。



Best Answer-推荐答案


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

关于ios - 无法在 UNNotificationContentExtension 上使用 AutoLayout 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40472293/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4