自定义带有quartz的UIBarButtonItem

4
我该如何使用Quartz绘制与UIBarButtonItem完全相同风格的按钮?该按钮应能显示不同的颜色。 我下载了Three20项目,但这个项目非常复杂,你需要花费很多时间来查看整个框架。我只想绘制自定义的UIBarButtonItem。
谢谢帮助。
3个回答

1
尝试使用仅一个片段和瞬时选择的UISegmentedControl。它支持tintColor,可能足够接近您的目的。

0
如果您正在使用Three20库,我猜TTButton的“toolbarButton”样式是您想要的。TTButton是UIButton的子类,但允许您在创建网页时像使用CSS一样应用样式。
要创建类似于UIBarButtonItem的按钮,只需调用
[TTButton buttonWithStyle:@"toolbarButton:" title:@"Title"]

由于该按钮是自动释放对象,您可能需要保留它。


0

在Swift 4.1中

您可以使用Quartz2D添加自己的自定义视图,包括自己的设计/动画/颜色等。

  • 使用自定义Quartz内容创建自定义视图
  • 使用自定义视图添加UIBarButtonItem
  • 添加协议(因为使用自定义视图初始化的UIBarButtonItem期望视图处理用户交互,因此不提供设置目标/选择器的方法)

通过此方法创建的工具栏按钮项不会在响应用户交互时调用其目标的操作方法。相反,工具栏按钮项期望指定的自定义视图处理任何用户交互并提供适当的响应。

不要忘记添加您的视图必须符合协议(在这种情况下是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()
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接