【发布时间】:2018-05-29 00:57:56
【问题描述】:
我正在处理几个需要以编程方式创建的自定义 UIControl 对象。通常在使用 AutoLayout 时,我只传递一个 CGRect。使用视觉格式语言时:
override init(frame: 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)
}
}
或者创建一个同时适用于 AutoLayout 和 VFL 的 UIControl 的最佳方法是什么?
【问题讨论】: