gpt4 book ai didi

ios - "Use of unresolved indentifier ' 自身 '"带按钮.addTarget

转载 作者:行者123 更新时间:2023-11-29 05:55:40 24 4
gpt4 key购买 nike

我是 Swift 的初学者。我创建了一个非常简单的按钮组件,但是当我尝试添加与按钮单击相关的函数时,我收到错误:“使用未解析的标识符‘self’。”这是我的代码:

import UIKit
import PlaygroundSupport


let containerView = UIView (frame: CGRect(x: 0, y: 0, width: 600, height: 600))
containerView.backgroundColor = UIColor.blue

let button = UIButton (frame: CGRect(x: 100, y: 100, width: 200, height: 200))
button.backgroundColor = UIColor.yellow
button.setTitle("Test Button", for: .normal)
button.setTitleColor(.red, for: .normal)
button.layer.cornerRadius = 10
func ButtonClicked(_ sender: UIButton) {
print()
}
button.addTarget(self, action: #selector(ButtonClicked), for: .touchUpInside)

containerView.addSubview(button)
PlaygroundPage.current.liveView = containerView

任何帮助将不胜感激,谢谢!

最佳答案

正如评论中提到的,由于您不在类或结构中工作,因此代码中没有可以引用的 self 。您要做的第一件事是将这些东西包装到一个类中,并对其进行一些重新组织。我建议返回 Xcode 并执行以下操作:

  1. 文件>新建> Playground ...
  2. 选择 iOS > 单一 View
  3. 将这个新的 Playground 保存在某个地方。

现在,您应该拥有一个根据模板创建的简单 Playground。在这里,您将能够看到如何创建一个继承于 UIViewController 的名为 MyViewController 的新类。在其中,您将找到一个名为 loadView() 的函数。然后,在类之外,您将看到这个新 View Controller 的创建位置并将其放置到 PlaygroundPage 的当前 liveView 中。

理想情况下,您应该能够单击代码 View 底部的“播放”按钮,如果助理编辑器打开,您将看到一个带有“Hello World!”的简单 View 。标签位于 View 的中心。 (助理按钮是带有两个互锁圆圈的按钮。)

Assistant Editor button

假设它运行并适合您,那么我建议您开始重新添加代码并尝试遵循模板中设置的模式。将设置 View 的代码放在 loadView() 函数中,并将 ButtonClicked() 函数移到该函数之外,但仍在类内。

经过一些修改,您应该能够启动并运行,并开始使用 Swift。作为示例,以下是 Playground 代码的工作版本:

    //: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
override func loadView() {

let containerView = UIView (frame: CGRect(x: 0, y: 0, width: 600, height: 600))
containerView.backgroundColor = UIColor.blue

let button = UIButton (frame: CGRect(x: 100, y: 100, width: 200, height: 200))
button.backgroundColor = UIColor.yellow
button.setTitle("Test Button", for: .normal)
button.setTitleColor(.red, for: .normal)
button.layer.cornerRadius = 10

button.addTarget(self, action: #selector(ButtonClicked), for: .touchUpInside)

containerView.addSubview(button)

self.view = containerView
}

@objc func ButtonClicked(_ sender: UIButton) {
print("ButtonClicked")
}
}

PlaygroundPage.current.liveView = MyViewController()

玩得开心,花一些时间阅读《Swift 编程指南》,事情很快就会变得有意义。

关于ios - "Use of unresolved indentifier ' 自身 '"带按钮.addTarget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55189810/

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