【问题标题】:Custom shape UIButton自定义形状 UIButton
【发布时间】:2017-03-05 09:18:47
【问题描述】:

我的时钟视图如下所示:

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

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

知道怎么做吗?

谢谢!

【问题讨论】:

  • 您可能需要检查CGContext API。
  • @AhmadF 你能更具体一点吗?我应该在那里搜索什么?
  • 尝试阅读类似于this one的文章,它向您展示了如何绘制形状。此外,现在 CGContext (Swift 3) 更容易使用。
  • @AhmadF 但我怎样才能画出这个精确的形状并将其放置在正确的位置?

标签: ios cocoa-touch uibutton


【解决方案1】:

您不需要按钮。您可以将时钟创建为单个 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

【讨论】:

  • 哇,你真是个天才!!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多