ios - 按钮 Playground swift

标签 ios swift

我只是想添加一个创建 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/

相关文章:

ios - 如何获取按索引配对的两个单独的 Int 数组的值,然后对某些对进行条件运算?

iphone - UIScrollView 和 UITextView 可以自动调整大小吗?

swift - 使用 Swift 将自定义字体添加到 macOS 应用程序

ios - 在 iOS 中,如何以编程方式添加视频 View ,然后在使用 Swift 完成播放后将其删除?

swift - 使用 NSURLSession 时 GET 成功,但使用 AFHTTPSessionManager 时 GET 失败

iphone - 如何在企业应用中使用InAppPurchase?

javascript - JSON 数据未出现在 iOS 中的响应 header 中

ios - 尝试使用 CIFilter 旋转/裁剪图像时,createCGImage 返回 nil

Swift - Tableviewcell删除图标自定义

ios - Swift:将选项卡栏放在 View 前面