gpt4 book ai didi

swift - 触摸手势识别器清除屏幕的随机功能

转载 作者:行者123 更新时间:2023-11-30 10:34:33 24 4
gpt4 key购买 nike

我正在 Xcode 中构建一个拼贴画,其中包含一组背景图像和一个随机 int 函数来显示图像。

我尝试使用 tapGestureRecognizer 1)显示随机图像并 2)在使用 self.clearScreen 后清除屏幕。图像正在显示,但在显示下一个图像时它们不会消失。

import UIKit
import C4

class WorkSpace: CanvasController {

override func setup() {


var myRandomNumber: Int?

//Background Image
let background = Image("background")
background?.constrainsProportions = true
background?.width = self.canvas.width
background?.height = self.canvas.height

self.canvas.add(background)

canvas.addTapGestureRecognizer { (locations, center, state) in
self.clearScreen
myRandomNumber = random(below: 4)
}
}

if myRandomNumber == 1 {
let tree = Image("Tree")
tree?.constrainsProportions = true
tree?.width = self.canvas.width
tree?.origin = Point(0.0, self.canvas.height/2.0)
self.canvas.add(tree)
print("number1")
}
if myRandomNumber == 2 {
let boy = Image("boy")
boy?.constrainsProportions = true
boy?.width = self.canvas.width
boy?.origin = Point(0.0, self.canvas.height/2.0)
self.canvas.add(boy)
}
if myRandomNumber == 3 {
let woman = Image("woman")
woman?.constrainsProportions = true
woman?.width = self.canvas.width
woman?.height = self.canvas.height
self.canvas.add(woman)
}
}
}

我希望屏幕清除图片并替换为其他图片。

func clearScreen() { 
for view in self.view.subView {
view.removeFromSuperView()
}
}

最佳答案

查看 C4 pods 后 docs :添加到 Canvas 后检查 View 层次结构

/// Adds a view to the end of the receiver’s list of subviews.
/// When working with C4, use this method to add views because it handles the addition of both UIView and View.
public func add<T>(_ subview: T?) {...}

然后尝试使用其提供的方法删除 subview :

/// Unlinks the view from the receiver and its window, and removes it from the responder chain.
/// Calling this method removes any constraints that refer to the view you are removing, or that refer to any view in the
/// subtree of the view you are removing.
/// When working with C4, use this method to add views because it handles the removal of both UIView and View.
/// ````
/// let v = View(frame: Rect(0,0,100,100))
/// let subv = View(frame: Rect(25,25,50,50))
/// v.add(subv)
/// v.remove(subv)
/// ````
/// - parameter subview: The view to be removed.
public func remove<T>(_ subview: T?) {
if let v = subview as? UIView {
v.removeFromSuperview()
} else if let v = subview as? View {
v.view.removeFromSuperview()
} else {
fatalError("Can't remove subview of class `\(type(of: subview))`")
}
}

关于swift - 触摸手势识别器清除屏幕的随机功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58357669/

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