【问题标题】:Create multiple UIViews when the user taps the screen当用户点击屏幕时创建多个 UIView
【发布时间】:2014-12-30 17:47:15
【问题描述】:

我想在用户点击屏幕时添加多个 UIView,我正在使用下面的代码,当我点击时它会创建一个 UIView,但会删除前一个。 我做错了什么?

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    let touch = touches.anyObject()! as UITouch
    let location = touch.locationInView(self.view)

    println(location)

    rectangle.frame = CGRectMake(location.x, location.y, 20, 20)
    rectangle.backgroundColor = UIColor.redColor()
    self.view.addSubview(rectangle)
}

【问题讨论】:

    标签: swift uiview touchesbegan


    【解决方案1】:

    假设rectangle 是一个属性,这段代码只改变了现有矩形的边框并将其重新添加到视图层次结构中。如果您希望每次用户开始触摸设备时都添加一个新矩形,您必须每次都创建一个新的 UIView 实例。例如:

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        let touch = touches.anyObject()! as UITouch
        let location = touch.locationInView(self.view)
    
        println(location)
    
        let rectangle = UIView(frame: CGRectMake(location.x, location.y, 20, 20))
        rectangle.backgroundColor = UIColor.redColor()
        self.view.addSubview(rectangle)
    }
    

    另外,如果这不是您的意图,您使用的代码不会将新视图居中于触摸位置,它的原点会在那里,但视图将从那里向下延伸 20 点,并且向右 20 点。如果您希望视图在触摸位置居中,我建议使用视图的 center 属性:

    let rectangle = UIView(frame: CGRectMake(0, 0, 20, 20))
    rectangle.center = location
    self.view.addSubview(rectangle)
    

    【讨论】:

    • 太棒了。这样可行。如果我想在之后编辑这些属性,我应该怎么做?我应该每次都将它们添加到数组中吗?
    • @TomCoomer 这会起作用,尽管应该提到它们每个都将被添加到 self.view.subviews 数组中,因此通过它可能更容易获得它们。只需使用对您的实施最有意义的方法即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多