我该如何使用Quartz绘制与UIBarButtonItem完全相同风格的按钮?该按钮应能显示不同的颜色。
我下载了Three20项目,但这个项目非常复杂,你需要花费很多时间来查看整个框架。我只想绘制自定义的UIBarButtonItem。
谢谢帮助。
谢谢帮助。
[TTButton buttonWithStyle:@"toolbarButton:" title:@"Title"]
由于该按钮是自动释放对象,您可能需要保留它。
在Swift 4.1中
您可以使用Quartz2D添加自己的自定义视图,包括自己的设计/动画/颜色等。
通过此方法创建的工具栏按钮项不会在响应用户交互时调用其目标的操作方法。相反,工具栏按钮项期望指定的自定义视图处理任何用户交互并提供适当的响应。
不要忘记添加您的视图必须符合协议(在这种情况下是CameraButtonDelegate
),并且还要添加方法cameraButtonChanged(to:)
以捕获用户交互。
func setupButton() {
customView = CameraButton()
customView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
customView.delegate = self
let barButtonItem = UIBarButtonItem(customView:customView)
self.navigationItem.rightBarButtonItem = torchItem
}
protocol CameraButtonDelegate {
func cameraButtonChanged(to state:Bool)
}
class CameraButton: UIView {
var delegate: CameraButtonDelegate?
var active: Bool = false
var strokeColor = UIColor.gray
init() {
self.init()
self.backgroundColor = .clear
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.active = self.active ? false : true
self.strokeColor = self.active ? UIColor.blue : UIColor.gray
setNeedsDisplay()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.delegate?.cameraButtonChanged(to: self.active)
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(strokeColor.cgColor)
context?.setLineWidth(1.0)
// Add your Quartz stuff here
context?.strokePath()
}
}