ios - 具有自动布局的 Swift UIView 子类

标签 ios swift autolayout

我正在创建一个新的自定义 UIView 子类,我想在其中为该 View 使用自动布局。该 View 包含一个标签。我的自定义 View 应根据文本大小自动调整大小。我的困惑是,这行得通吗?我必须用框架初始化我的自定义 View 吗?

class CustomView : UIView
{
    var label : UILabel = UILabel()
    
    var text : String = ""
    
    init(text: String)
    {
        super.init(frame: .zero)

        self.text = text
        
        setupView()
        setupLayout()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("This class does not support NSCoding")
    }
    
    func setupView() -> Void
    {
        self.backgroundColor = UIColor(red: 85.0/255.0, green: 88.0/255.0, blue: 91.0/255.0, alpha: 1.0)
        
        //Create main label
        let label = UILabel()
        label.text = self.text
        label.textColor = .white
        label.font = label.font.withSize(12.0)
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        label.textAlignment = .left
        self.label = label
        addSubview(label)
    }
    

    override class var requiresConstraintBasedLayout: Bool {
        return true
    }
    
    func setupLayout() -> Void
    {
        label.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            label.topAnchor.constraint(equalTo: topAnchor),
            label.bottomAnchor.constraint(equalTo: bottomAnchor),
            label.trailingAnchor.constraint(equalTo: trailingAnchor),
            label.leadingAnchor.constraint(equalTo: leadingAnchor),
            widthAnchor.constraint(equalToConstant: 200),
            heightAnchor.constraint(equalToConstant: 200)
        ])
    }
}
这是我尝试过的..我创建了一个自己的init()方法,我将零帧传递给 super 初始化。那是对的吗?我希望根据文本通过自动布局来完成大小。或者我是否需要在使用 CustomView 的父 View 中设置约束。

最佳答案

为什么要给标签 heightAnchor?
如果您希望它自动调整大小取决于文本,您要做的就是:

  • 对于标签
  • ,numberOfLines 为 0
  • 将标签的顶部、前导、底部和尾随 anchor 提供给其 super View
  • super View 至少应该有顶部、前导和尾随 anchor 到您要添加此自定义 View 的 super View ( View Controller View )。

  • 不要忘记在初始化自定义 View 时将属性 translatesAutoresizingMaskIntoConstraints 设置为 false

    关于ios - 具有自动布局的 Swift UIView 子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63987788/

    相关文章:

    ios - 当我有多个 iOS 部分时从 UITableView 中删除行(值在 Dynamic NSMutableDictionary 中)

    ios - Firebase iOS SDK - 使用 GoogleService-Info.plist 以外的配置文件会生成控制台警告

    ios - CoreLocation查找行进距离并用作iOS变量

    ios - UISplitViewController - 设置始终可见的主 Controller

    ios - 自动布局不会减少顶部约束

    ios - 激活/停用自动布局 NSLayoutConstraints

    ios - Adobe Air App 最低 IOS 版本

    ios - SwiftUI 填充距离不一致

    ios - 无法访问包中的文件

    带有 NavigationLink 的 Swift onTapGesture