ios - 创建应用程序以在用户点击 View 时创建圆圈

标签 ios swift uitouch

我想问一下是否有人能弄清楚我的代码有什么问题,当有触摸事件时我似乎无法创建一个圆圈。

override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.lightGray
    // Do any additional setup after loading the view, typically from a nib.

}

func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch = touches as? Set<UITouch> {

        let circleCenter = touch.first!.location(in: view)

        let circleWidth = CGFloat(25)
        let circleHeight = circleWidth

        let circleView = CircleView(frame: CGRect(x: circleCenter.x, y: circleCenter.y, width: circleWidth, height: circleHeight))
        view.addSubview(circleView)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

如果您需要我的 subview CircleView代码:

class CircleView: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.clear
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func draw(rect: CGRect) {

    var context = UIGraphicsGetCurrentContext();

    context!.setLineWidth(5.0)

    UIColor.red.set()

    let center = CGPoint(x: round(frame.size.width)/(2), y: round(frame.size.height)/2)
    let radius = (round(frame.size.width) - 10)/(2)

    context!.addArc(center:center, radius:radius, startAngle:0, endAngle:CGFloat(Double.pi) * 2, clockwise:true)

    context!.strokePath();

    }

最佳答案

您的两个函数不正确(截至 Swift 3)。变化

func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)

和改变

func draw(rect: CGRect)

override func draw(_ rect: CGRect)

关于ios - 创建应用程序以在用户点击 View 时创建圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46177819/

相关文章:

iphone - iOS 实时音频 I/O

ios - 当用户将手指拖动到新 View 时,如何在不同 View 上注册触摸?

ios - PDFview 在单页文档中滚动到页面底部

iphone - CoreFoundation 中的 CFStringGetLength 导致 iOS 崩溃

ios - 删除单元格和标题之间的空间

Swift SDWebImage 从不执行完成

ios - Swift - TableView 将 IndexPath 返回为 nil

ios - 通过快速手指移动检测 View 中的所有触摸位置

ios - 检测选定的 UIImageView

ios - 返回表中的单元格数会产生 NSInternalInconsistenceyException