我只是想添加一个创建 View 的按钮操作。 有人可以帮助我吗?
import UIKit
import PlaygroundSupport
class ViewController : UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.black
navigationController?.isNavigationBarHidden = true
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = UIColor.white
view.addSubview(button)
class Button: ViewController {
@objc func fbtn () {
let newView = UIView()
newView.backgroundColor = UIColor.yellow
view.addSubview(newView)
}
}
button.addTarget(button, action: #selector(Button.fbtn), for: .touchUpInside)
}
}
PlaygroundPage.current.liveView = UINavigationController(rootViewController: ViewController())
最佳答案
您的嵌套 Button
类似乎没有意义。只需将 fbtn
设为 ViewController
类的函数即可。并使 self
成为按钮操作的目标。
class ViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
navigationController?.isNavigationBarHidden = true
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.backgroundColor = .white
view.addSubview(button)
button.addTarget(self, action: #selector(fbtn), for: .touchUpInside)
}
@objc func fbtn() {
let newView = UIView()
newView.backgroundColor = .yellow
view.addSubview(newView)
}
}
此外,在 fbtn
函数中为 newView
提供一个有用的框架。
关于ios - 按钮 Playground swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433329/