|
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() |
|
} |
|
} |
|
|
|
} |