首页 > 解决方案 > 如何在启用 translatesAutoresizingMaskIntoConstraints 的情况下布局视图

问题描述

据我了解,有一种新方法可以为 iOS 14 配置 UITableView 单元格。我正在使用这种方法,但是当我实现它时,出现了错误。

Exception NSException * "The content view returned from the content configuration must have translatesAutoresizingMaskIntoConstraints enabled"

但是,当我设置translatesAutoresizingMaskIntoConstraints为 true 时,我无法再为单元格布局视图。也就是说,即使我设置了视图的宽度,也没有显示任何内容。

下面是我正在使用的方法(没有配置视图的代码)。我的问题是是否有办法在仍然能够布局视图的同时避免错误。

@available(iOS 14, *)
extension GoalCell {

    struct Configuration: UIContentConfiguration {
        
        func makeContentView() -> UIView & UIContentView {
            return MyContentView(configuration: self)
        }
        func updated(for state: UIConfigurationState) -> GoalCell.Configuration {
            return self
        }
    }
    
    class MyContentView: UIView, UIContentView {
        var configuration: UIContentConfiguration {
            didSet {
                self.configure()
            }
        }
        }()
        init(configuration: UIContentConfiguration) {
            self.configuration = configuration
            super.init(frame: .zero)
            
            self.configure()
        }
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        private func configure() {
            guard let config = self.configuration as? Configuration else { return }
            
            self.translatesAutoresizingMaskIntoConstraints = true
        }
    }

标签: swiftuitableviewios14

解决方案


推荐阅读