FS.O6 FS.O6 - 1 month ago 17
iOS Question

Custom shape UIButton

I have a clock view that looks like this:

Clock

I want to add a

UIButton
between every hour (12-1, 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-9, 9-10, 10-11, 11-12) that will look like this:

Button

Example of a clock that has 1 button:

Clock with button

Any idea how to do it?

Thanks!

Answer

You do not need buttons. You can create your clock as a single UIView and add a touch gesture recognizer to it. Use trigonometry to convert the touch point to the clock section

class ClockView: UIView {
    override func awakeFromNib() {
        super.awakeFromNib()
        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapClock)))
    }

@objc private func tapClock (tapGestureRecognizer: UITapGestureRecognizer) {
    let touchPoint = tapGestureRecognizer.location(in: self)

    let delta = CGPoint(x: center.x - touchPoint.x, y: center.y - touchPoint.y)
    let distance = hypotf(Float(delta.x), Float(delta.y))
    //Ignore points outside circle
    guard distance < Float(min (frame.width / 2, frame.height / 2)) else {
        return
    }
    let angle = atan2f(Float(delta.y), Float(delta.x))
    let proportion = angle / (Float.pi * 2) + 0.5
    let hour = (Int(proportion * 12) + 3) % 12 + 1
    print (hour)
}

}

You can follow this tutorial to draw the clock: http://sketchytech.blogspot.com/2014/11/swift-how-to-draw-clock-face-using.html

Comments