Swift Today Extension preferredContentSize 未调整大小

Swift Today Extension preferredContentSize not resizing

就像描述中说的那样,我正在开发一个 iOS 应用程序,并想为其创建一个 Today Extension Widget。我的问题是我想将高度更改为 200。在研究之后,我发现唯一的解决方案是使用 preferredContentSize 属性,但这对我不起作用。

我想给它添加一个 table 视图,我希望它应该完全显示。 我添加了 viewDidLoad 方法,这样您就可以看到 table 的创建和添加位置。

override func viewDidLoad() {
    super.viewDidLoad()

    let myDefaults = UserDefaults(suiteName: "group.com.iOSApp")!
    let eventData = myDefaults.object(forKey: "events")

    if eventData != nil {
        shownEvents = NSKeyedUnarchiver.unarchiveObject(with: eventData as! Data) as! [Event]
    }

    eventTable = UITableView()
    eventTable.register(TodayViewCell.self, forCellReuseIdentifier: "cell")
    eventTable.separatorColor = UIColor.primary()
    view.addSubview(eventTable)
    eventTable.translatesAutoresizingMaskIntoConstraints = false

    var tempX = NSLayoutConstraint(item: eventTable, attribute: .leading, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)
    var tempY = NSLayoutConstraint(item: eventTable, attribute: .top, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .top, multiplier: 1, constant: 0) 
    NSLayoutConstraint.activate([tempX, tempY])

    tempX = NSLayoutConstraint(item: eventTable, attribute: .trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
    tempY = NSLayoutConstraint(item: eventTable, attribute: .bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)   
    NSLayoutConstraint.activate([tempX, tempY])


    eventTable.delegate = self
    eventTable.dataSource = self

    eventTable.reloadData()

    preferredContentSize.height = 200


}

在iOS10设置preferredContentSize.height直接不行

在iOS10之后,有两种类型显示今天的延期

案例一显示更多(展开类型,可自定义高度)

case 2 Show Less (compact type, has default hegiht)

What's new in iOS 10

所以你应该为 iOS 10 个早期版本和 iOS 10

提供高度
if #available(iOSApplicationExtension 10.0, *) {
        //setup display mode (show more(.expended) or show less(.compact))
        extensionContext?.widgetLargestAvailableDisplayMode = .expanded
    } else {
        // Fallback on earlier versions
        preferredContentSize.height = 200
    }

并应实现自定义高度

func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {

@available(iOSApplicationExtension 10.0, *)
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
    switch activeDisplayMode {
    case .expanded: preferredContentSize.height = 200
    case .compact: preferredContentSize = maxSize
    }
}