使用编程VFL约束初始化UIControl(iOS Swift)

使用编程VFL约束初始化UIControl(iOS Swift),ios,swift,xcode9,Ios,Swift,Xcode9,我正在处理几个需要以编程方式创建的自定义UIControl对象。通常在使用AutoLayout时,我只传递一个CGRect。使用视觉格式语言时,请执行以下操作: override init(帧:CGRect){ super.init(frame:frame) updateLayer() } 在UIControl类中,ViewDidLoad()中的约束方法不会调用,并且不会更新CAShapeLayers。自定义按钮/滑块/旋钮等可以工作,但不可见,我可以在触摸后立即更新形状。不是很有帮助。如何在加

我正在处理几个需要以编程方式创建的自定义UIControl对象。通常在使用AutoLayout时,我只传递一个CGRect。使用视觉格式语言时,请执行以下操作:

override init(帧:CGRect){
super.init(frame:frame)
updateLayer()
}

在UIControl类中,ViewDidLoad()中的约束方法不会调用,并且不会更新CAShapeLayers。自定义按钮/滑块/旋钮等可以工作,但不可见,我可以在触摸后立即更新形状。不是很有帮助。如何在加载视图后立即在屏幕上显示使用VFL的自定义UIControl?这就是我想做的:

import UIKit

class ViewController: UIViewController {

   let knob = Knob()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(knob)
        knob.translatesAutoresizingMaskIntoConstraints = false
        let views = [
            "slider": knob
        ]

        let formatV = "V:|-[knob(300)]-|"
        let formatH = "H:|-[knob(300)]-|"

        let VC = NSLayoutConstraint.constraints(withVisualFormat: formatV, options: NSLayoutFormatOptions(), metrics: nil, views: views)
        let HC = NSLayoutConstraint.constraints(withVisualFormat: formatH, options: NSLayoutFormatOptions(), metrics: nil, views: views)

        self.view.addConstraints(VC)
        self.view.addConstraints(HC)
        knob.addTarget(self, action: #selector(knobRotated(_:)), for: .touchDown)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @objc func knobRotated(_ sender: Knob) {
        print(sender.value)
    }
}

或者,创建同时适用于自动布局和VFL的UIControl的最佳方法是什么?

UIControl
UIView
的子类,因此在外观方面对它们进行相同的处理。您可以使用
CALayer
UIView
可视化控件;根据对象的参与程度,我使用这两种方法。例如,当我创建自定义开关时,我专门使用图层,当我为按钮创建子类时,我专门使用视图

下面的简单按钮示例演示了一般概念

class MenuButton: UIControl {


    private let button = UIView()
    private let buttonLabel = UILabel()
    private let buttonCaption = UILabel()
    var menuName = ""


    // MARK: Lifecycle


    override init(frame: CGRect) {
        super.init(frame: frame)

        config()
        addButton()
        addButtonLabel()
        addButtonCaption()

    }


    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }


    override func updateConstraints() {
        super.updateConstraints()

        button.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        button.topAnchor.constraint(equalTo: topAnchor).isActive = true
        button.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
        button.heightAnchor.constraint(equalToConstant: 48).isActive = true

        buttonLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        buttonLabel.topAnchor.constraint(equalTo: topAnchor).isActive = true
        buttonLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -48).isActive = true
        buttonLabel.heightAnchor.constraint(equalToConstant: 48).isActive = true

        // if you have a label with varying height, for example,
        // adding the text where the label was created will not allow
        // autolayout to account for it so you must add it later in
        // the object's lifecycle, like here
        buttonCaption.text = menuName

        buttonCaption.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        buttonCaption.topAnchor.constraint(equalTo: button.bottomAnchor, constant: 4).isActive = true
        buttonCaption.widthAnchor.constraint(equalTo: widthAnchor, constant: -16).isActive = true
        buttonCaption.sizeToFit()

        // i don't know if this is necessary but I always do it, but
        // the key to making autolayout work for you (i.e. scroll view
        // content size, table view cells, collection view cells) is 
        // to chain constraints together so that the top-most view is
        // touching the top of its container and the bottom-most view
        // is touching the bottom of its container and autolayout will
        // (or should) always auto size the container
        buttonCaption.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

        // or replace with your visually-formatted autolayout constraints

    }


    // layout subviews
    override func layoutSubviews() {
        super.layoutSubviews()

        setButtonLabelText(selectedOptions: selectedOptions)

    }


    // MARK: Methods


    private func config() {

        isOpaque = false
        isExclusiveTouch = true

    }


    private func addButton() {

        button.isUserInteractionEnabled = false
        button.backgroundColor = UIColor.blue
        button.layer.cornerRadius = 8
        button.translatesAutoresizingMaskIntoConstraints = false
        addSubview(button)

    }


    private func addButtonLabel() {

        buttonLabel.numberOfLines = 1
        buttonLabel.lineBreakMode = .byTruncatingTail
        buttonLabel.font = UIFont.menuLabel
        buttonLabel.minimumScaleFactor = (20/23)
        buttonLabel.textColor = UIColor.menuLabel
        buttonLabel.textAlignment = .center
        buttonLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(buttonLabel)

    }


    private func addButtonCaption() {

        buttonCaption.numberOfLines = 0
        buttonCaption.font = UIFont.displayBold(size: 16)
        buttonCaption.textColor = UIColor.text.withAlphaComponent(0.25)
        buttonCaption.textAlignment = .left
        buttonCaption.translatesAutoresizingMaskIntoConstraints = false
        addSubview(buttonCaption)

    }


    func setButtonLabelText(selectedOptions: [Int]) {

        // add logic

    }


}
例如,当我子类化
UIControl
以进行切换时,我不关心自动布局,因此我将专门使用层并明确声明其大小:

override open var intrinsicContentSize: CGSize {
    return CGSize(width: 60, height: 30)
}
然后在视图基本就绪后,使用
layoutSubviews
设置交换机的状态:

override open func layoutSubviews() {
    super.layoutSubviews()

    if isOn {

        thumbLayer.position = onPosition
        thumbLayer.backgroundColor = onColor

    } else {

        thumbLayer.position = offPosition
        thumbLayer.backgroundColor = offColor

    }

}

子类化对象就是了解生命周期。在每个生命周期方法中打印到控制台,以查看它们何时启动。

非常感谢!这就是我所需要的:覆盖openfunc layoutSubviews(){super.layoutSubviews()updateLayer()}虽然OP说了谢谢,但我注意到你的答案中没有VFL。这不是对问题的糟糕回答,更可能是对一个糟糕问题的正确回答。他的问题与理解对象的生命周期有关,而不是VFL。约束就是约束,不管它们是否被可视化格式化,在这里都是无关的。