swift - 在 Swift 4 中以编程方式创建 UIButton 但出现错误
问题描述
我正在尝试在 Swift 4 中创建一个 UIButton,但是当我尝试调用 addTarget 函数时,我在“MyView”类中不断收到“预期声明”错误。我已经在其他类中完成了相同的代码,并且从未收到错误。我错过了什么吗?谢谢。
import Foundation
import UIKit
protocol MyDelegate: class {
func onButtonTapped()
}
class OtherViewController: UIViewController {
}
class MyViewController: UIViewController, MyDelegate {
func onButtonTapped() {
let nextViewController = OtherViewController()
navigationController?.pushViewController(nextViewController, animated: false)
}
var myView: MyView!
override func viewDidLoad() {
super.viewDidLoad()
myView.delegate = self
}
}
class MyView: UIView {
weak var delegate: MyDelegate?
let button = UIButton()
button.addTarget(self, action: #selector(buttonTapped),for: .touchUpInside)
func buttonTapped() {
self.delegate?.onButtonTapped()
}
}
解决方案
您不能 addTarget 或调用类空间中的任何方法,此空间用于声明错误提示。
要解决这个问题,你可以这样做
let button:UIButton =
{
let btn = UIButton()
btn.addTarget(self, action: #selector(buttonTapped),for: .touchUpInside)
return btn
}()
或者
let button:UIButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
button.addTarget(self, action: #selector(buttonTapped),for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
在这两种情况下,您都必须将 @objc 注释添加到 buttonTapped 函数,因为选择器必须引用 @objc 函数。
所以会是这样
@objc func buttonTapped(){}
您还需要将此按钮添加到视图中,以便将其绘制到屏幕上。
view.addSubView(button)
推荐阅读
- html - 我应该如何更改移动设备的 React 输入按钮宽度?
- powerbi - 使用 DAX 和 3 个上下文的嵌套 If Problem
- reactjs - Material UI - 将道具应用于伪元素
- amazon-web-services - AWS Route53 子域间歇性关闭
- mongodb - 添加更多属性时未使用 Mongo 索引
- html - 材质图标对齐问题
- html - 如何从材料设计概述的文本字段中删除占位符
- java - 无论如何通过意图在android studio中打开秘密网络设置?
- c# - VS Code 无法在 unity3D 中捕获断点
- linux - 使用 Electron Builder 构建 appImage 时出现“不允许符号链接操作”错误