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

时间:2017-01-07 17:10:16

标签: ios autolayout nslayoutconstraint today-extension

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

有趣的事情:看起来他们在iOS 10中展示新功能时遇到了错误(https://developer.apple.com/videos/play/wwdc2016/101/?time=3221

虽然实现了这个,我仍然没有得到正确的高度调整。请参阅下面的相关代码详细信息,并查看完整的源代码:https://github.com/everlof/TodayExtensionSample

.Expanded

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) } 中的扩展名为STARTED,则看起来是正确的:

enter image description here

如果按下“显示更少”,它看起来是正确的:

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:2)

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

根据您的代码,在扩展模式下,您将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
    }
}