Skip to content

Instantly share code, notes, and snippets.

@NeedMoreDesu
Created May 26, 2016 14:25
Show Gist options
  • Save NeedMoreDesu/18367a45a1149a778f1233d1629773f3 to your computer and use it in GitHub Desktop.
Save NeedMoreDesu/18367a45a1149a778f1233d1629773f3 to your computer and use it in GitHub Desktop.
import UIKit
class BlockBarButtonItem : UIBarButtonItem {
private var actionHandler: ((Void) -> Void)?
convenience init(image: UIImage?, actionHandler: ((Void) -> Void)?) {
self.init(image: image, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.target = self
self.action = #selector(BlockBarButtonItem.barButtonItemPressed(_:))
self.actionHandler = actionHandler
}
convenience init(title: String?, actionHandler: ((Void) -> Void)?) {
self.init(title: title, style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.target = self
self.action = #selector(BlockBarButtonItem.barButtonItemPressed(_:))
self.actionHandler = actionHandler
}
convenience init(image: UIImage?, title: String?, actionHandler: ((Void) -> Void)?) {
let view = UIView(frame: CGRectMake(0, 0, 80, 31))
let button = UIButton(frame: CGRectMake(0, 0, 80, 31))
button.setImage(image, forState: UIControlState.Normal)
button.setImage(image, forState: UIControlState.Highlighted)
button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
button.tintColor = UINavigationBar.appearance().tintColor
let label = UIButton(frame: CGRectMake(20, 0, 80, 31))
label.titleLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingTail
label.setTitle(title, forState: UIControlState.Normal)
label.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
label.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
label.userInteractionEnabled = false
label.setTitleColor(UINavigationBar.appearance().tintColor, forState: UIControlState.Normal)
button.addSubview(label)
view.addSubview(button)
self.init(customView: view)
button.addTarget(self, action: #selector(BlockBarButtonItem.barButtonItemPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.actionHandler = actionHandler
}
func barButtonItemPressed(sender: UIBarButtonItem) {
if let actionHandler = self.actionHandler {
actionHandler()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment