【问题标题】:Can't use AutoLayout Constraints on UNNotificationContentExtension无法在 UNNotificationContentExtension 上使用 AutoLayout 约束
【发布时间】:2016-11-07 18:42:18
【问题描述】:

我正在尝试在 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) {

    }

}

看起来像这样: 但是当我尝试使用此代码以编程方式(使用 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) {

    }

}

结果是这样的:

什么会导致 AutoLayout 在此视图控制器中不起作用?我也用界面生成器测试过,所以我很困惑。

【问题讨论】:

    标签: ios swift autolayout ios10 unusernotificationcenter


    【解决方案1】:

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

    【讨论】:

    • 这绝对是我错过的,但它仍然没有解决问题。如果我将 self.view 的背景颜色设置为黑色,则背景符合我的预期。一旦我向 myView 添加一个约束,我就会得到一个空白屏幕。
    猜你喜欢
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 2014-05-20
    • 1970-01-01
    • 2013-12-11
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多