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

时间:2017-12-14 20:47:02

标签: ios swift xcode9

我正在处理几个需要以编程方式创建的自定义UIControl对象。通常在使用AutoLayout时我只传递一个CGRect。使用Visual Format语言时:

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

在ViewDidLoad()中,约束方法不调用UIControl类中的

,并且不更新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)
    }
}

或者创建适用于AutoLayout和VFL的UIControl的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

UIControlUIView的子类,因此在外观上对它们进行相同的处理。您可以使用CALayerUIView来显示控件。我根据对象的使用方式使用它们。当我制作自定义开关时,我只使用图层,当我将按钮子类化时,我会使用视图,例如。

以下简单按钮示例演示了一般概念。

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

    }

}

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