|
// |
|
class CartButtonView: UIButton { |
|
let image = #imageLiteral(resourceName: "cart") |
|
var count:NSString = "0" |
|
|
|
override init(frame: CGRect) { |
|
super.init(frame: frame) |
|
} |
|
|
|
required init?(coder aDecoder: NSCoder) { |
|
super.init(coder: aDecoder) |
|
} |
|
|
|
|
|
func updateCount(notification:Notification) { |
|
if let count = notification.object as? String { |
|
self.count = count as NSString |
|
self.setNeedsDisplay() |
|
} |
|
} |
|
|
|
func registerObserver() { |
|
NotificationCenter.default.addObserver(self, selector: #selector(updateCount), name: NSNotification.Name(rawValue: "updateCount"), object: nil) |
|
} |
|
|
|
func unregisterObserver() { |
|
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "updateCount"), object: count) |
|
} |
|
|
|
deinit { |
|
unregisterObserver() |
|
} |
|
|
|
|
|
override func willMove(toSuperview newSuperview: UIView?) { |
|
if newSuperview == nil { |
|
unregisterObserver() |
|
}else { |
|
registerObserver() |
|
} |
|
} |
|
|
|
override func draw(_ rect: CGRect) { |
|
super.draw(rect) |
|
// obtain context |
|
let ctx = UIGraphicsGetCurrentContext() |
|
// make insets before drawing image |
|
let newRect = CGRect(x: 2, y: 10, width: self.frame.width - 10, height: self.frame.height - 10) |
|
//ctx?.draw(image.cgImage!, in: newRect) |
|
image.draw(in: newRect) |
|
// decide on radius |
|
var circleRect = CGRect(x:self.frame.width - 20 , y: 2, width: 20, height: 20) |
|
let circleCenter = CGPoint(x: self.frame.width - circleRect.width/2.0 , y: circleRect.width/2.0) |
|
|
|
let rad = CGFloat(10) |
|
let endAngle = CGFloat(2 * Double.pi) |
|
// add the circle to the context |
|
ctx?.addArc(center: circleCenter, radius: rad, startAngle: 0, endAngle: endAngle, clockwise: true) |
|
// set fill color |
|
ctx?.setFillColor(UIColor.red.cgColor) |
|
// set stroke color |
|
ctx?.setStrokeColor(UIColor.white.cgColor) |
|
// set line width |
|
ctx?.setLineWidth(0.0) |
|
// draw the path |
|
ctx?.drawPath(using: .fillStroke) |
|
|
|
let textFont = UIFont(name: "Lato" , size: 12) |
|
let textFontAttributes = [ |
|
NSFontAttributeName: textFont!, |
|
NSForegroundColorAttributeName: UIColor.white, |
|
|
|
] as [String : Any] |
|
let size = count.size(attributes: textFontAttributes) |
|
let diff = circleRect.width - size.width |
|
circleRect.origin.x = circleRect.origin.x + diff/2.0 |
|
count.draw(in: circleRect, withAttributes: textFontAttributes) |
|
//ctx?.closePath() |
|
} |
|
} |