创建应用以在用户点按视图时创建圈子

时间:2017-09-12 13:31:24

标签: 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.
}

如果您需要我的子视图代码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();

    }

2 个答案:

答案 0 :(得分:0)

您的两个功能不正确(截至 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)

答案 1 :(得分:-1)

正如@ the4kman所提到的,这是viewcontroller

所需要的
private static int? GetIntPattern(string text) {
    var m = Regex.Match(text, @"(\d{2})\D*$");
    int res;
    return m != null && int.TryParse(m.Groups[1].Value, out res) ? (int?)res : null;
}

并在你的CircleView中

\D*$