自定义形状UIButton

时间:2016-10-23 14:37:51

标签: ios cocoa-touch uibutton

我有一个如下所示的时钟视图:

Clock

我想在每小时之间添加一个UIButton(12-1,1-2,2-3,3-4,4-5,5-6,6-7,7-8,8 -9,9-10,10-11,11-12)看起来像这样:

Button

具有1个按钮的时钟示例:

Clock with button

知道该怎么做吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

您不需要按钮。您可以将时钟创建为单个UIView,并为其添加触摸手势识别器。使用三角法将触摸点转换为时钟部分

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

}

您可以按照本教程绘制时钟:http://sketchytech.blogspot.com/2014/11/swift-how-to-draw-clock-face-using.html