gpt4 book ai didi

swift - 当用户点击屏幕时创建多个 UIView

转载 作者:行者123 更新时间:2023-11-30 10:19:46 25 4
gpt4 key购买 nike

我想在用户点击屏幕时添加多个 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)
}

最佳答案

假设 rectangle 是一个属性,此代码仅更改现有矩形的框架并将其重新添加到 View 层次结构中。如果您希望在每次用户开始触摸设备时添加一个新的矩形,则必须每次创建一个新的 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)
}

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

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

关于swift - 当用户点击屏幕时创建多个 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27710085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com