在今日扩展中使用自动布局的dynamic高度

编辑:我的“原始”的问题已被解决,它被限制在110高度, "<NSAutoresizingMaskLayoutConstraint:0x6000000985b0 h=--& v=--& UIView:0x7fc83af0aeb0.height == 110 (active)>"之前我读了关于NCWidgetDisplayMode.Compact.Expanded ,这显然是在iOS 10中引入的。

有趣的事情:当他们在iOS 10中展示新function时,看起来像是有错误( https://developer.apple.com/videos/play/wwdc2016/101/?time=3221 )

尽pipe如此,我仍然没有得到正确的高度调整。 请参阅下面的相关代码细节,并查看完整的源代码: https : //github.com/everlof/TodayExtensionSample 。

 override func viewDidLoad() { super.viewDidLoad() extensionContext?.widgetLargestAvailableDisplayMode = .expanded view.backgroundColor = .red lbl.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin vitae tempor nulla, in volutpat lectus. Sed quis orci sit amet velit cursus congue non accumsan turpis. Phasellus quis augue lobortis, pharetra arcu vitae, condimentum nunc. Nam rutrum massa ac feugiat eleifend. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec non erat orci. Ut consequat faucibus sapien, et luctus magna posuere tempor." lbl.numberOfLines = 0 lbl.backgroundColor = .blue lbl.translatesAutoresizingMaskIntoConstraints = false } 

widgetActiveDisplayModeDidChange (它返回零高度,以便它使用自动布局):

 func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if activeDisplayMode == .expanded { print("EXPANDED") preferredContentSize = CGSize(width: 0.0, height: 0.0) setupLabel() } else if activeDisplayMode == .compact { print("COMPACT") preferredContentSize = maxSize setupLabel() } } 

setupLabel (删除它并添加它):

 func setupLabel() { lbl.removeFromSuperview() view.addSubview(lbl) lbl.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 18).isActive = true lbl.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -18).isActive = true lbl.topAnchor.constraint(equalTo: view.topAnchor, constant: 18).isActive = true lbl.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -18).isActive = true lbl.setContentCompressionResistancePriority(1000, for: .vertical) } 

如果扩展名是以.expanded STARTED的,看起来是正确的:

在这里输入图像说明

如果按下“Show less”,看起来是正确的:

在这里输入图像说明

然而,如果按下“显示更多”,则不会再次展开:

在这里输入图像说明

这是因为当您按“显示更多”时widgetActiveDisplayModeDidChange expanded activeDisplayMode调用widgetActiveDisplayModeDidChange方法。

根据您的代码,在扩展模式下,您将preferredContentSize设置为:

 preferredContentSize = CGSize(width: 0.0, height: 0.0) 

所以,它需要小部件允许的最小高度,即110。

尝试这个:

 func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if activeDisplayMode == .expanded { let size = self.sampleLabel.systemLayoutSizeFitting(self.sampleLabel.bounds.size) preferredContentSize = CGSize(width: 0.0, height: size.height) } else { preferredContentSize = maxSize } }