以编程方式定义通知内容扩展的高度

Programmatically defining the height of a notification content extension

通知扩展的width:height比率可以通过扩展的Info.plist文件中的属性UNNotificationExtensionInitialContentSizeRatio来定义。但是在加载相应的 UIViewController 之后,这个值可以以某种方式改变吗?

苹果网站上的documentation表示确实可以:

You can change the size of your view controller after your extension loads.

但是怎么办?我试过更改扩展程序的主要 UIView 框架,就像这样...

func didReceive(_ notification: UNNotification) {

    self.view.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 100.0)
    self.view.setNeedsUpdateConstraints()
    self.view.setNeedsLayout()
}

...但只有视图的框架被正确更新,整个通知容器底部留有空白区域。

我还尝试了一些不太明显的解决方案,包括在控制器生命周期的不同点更改框架以及直接设置 UIWindow 的框架。 None 到目前为止都成功了。

是否可以通过编程更改高度?

提前感谢您的回答。

您可以使用 UIViewController 的 preferredContentSize 属性 覆盖大小。

 func didReceive(_ notification: UNNotification) {

    self.preferredContentSize = CGSize(width: UIScreen.main.bounds.size.width, height: 200)
    self.view.setNeedsUpdateConstraints()
    self.view.setNeedsLayout() 
  // Image downloading work or other logic
}

如果您为所有控件正确设置了自动布局,通知将自行正确调整大小。无需调用任何调整大小代码。