iOS Swift 按钮在 View 中没有响应

标签 ios swift uibutton

我编写了一个类,其中显示的 View 具有 UITextView 和几个按钮。一切正常,除了按钮不响应水龙头。以下是我认为是我类(class)的相关代码:

class FullPrompt:UIViewController {
    var canceledPressedCallback:(()->()?)?=nil
    var okPressedCallback:((_ txt: String)->()?)? = nil
    var popupView = UIView()
    var field = UITextView()
    var parentView = UIView()

    func prompt(_ message:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->()) {
        prompt(message, view: view, numberInput: numberInput, callback: callback,cancelCallback: nil,defaultText: "")
    }

    func prompt(_ prompt:String,view: UIViewController,numberInput: Bool, callback: @escaping (_ txt: String)->(), cancelCallback: (()->())?,defaultText: String) {
        canceledPressedCallback=cancelCallback
        okPressedCallback=callback

        let cancelButton=UIButton(frame: CGRect(x: 10, y: y, width: 70, height: 32))
        cancelButton.setTitle("Cancel", for: .normal)
        cancelButton.addTarget(self, action: #selector(cancelButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(cancelButton)
        let okButton=UIButton(frame: CGRect(x: 210, y: y, width: 70, height: 32))
        okButton.setTitle("Ok", for: .normal)
        okButton.setTitleColor(UIColor.blue, for: .normal)
        okButton.addTarget(self, action: #selector(okButtonPressed(_:)), for: .touchUpInside)
        popupView.addSubview(okButton)
        view.view.addSubview(popupView)
    }

    func cancelButtonPressed(_ sender: UIButton ) {
        popupView.removeFromSuperview()
        if canceledPressedCallback != nil {
            canceledPressedCallback!()
        }
    }

    func okButtonPressed(_ sender: UIButton) {
        popupView.removeFromSuperview()
        okPressedCallback!(field.text)
    }
}

我做错了什么?

最佳答案

我明白了。我的错误是在我的类中添加了一个 View 属性 (popupView)。因为我的类是 UIViewController 的子类,所以我需要将我的 subview 添加到该类的 View 属性中,而不是创建另一个 View 。所以,基本上,无论我向 popupView 添加什么,我只是用 self.view 替换它。他们的按钮工作正常。

关于iOS Swift 按钮在 View 中没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47274713/

相关文章:

ios - removeFromSuperview() 并不总是有效

swift - Q : How do I move objects down the y axis as my player moves up?

ios - 如何根据实现该协议(protocol)的两个实例的身份为协议(protocol)实现 Equatable 协议(protocol)?

swift - 使用 Swift 通过 REST API 为 youtube 上传设置片段数据

ios - 将 UIButton 添加到工具栏 swift 5

javascript - UIButton 可以用来在 UIWebView 中执行超链接单击吗?

ios - UICollectionView @required 方法什么时候被调用?

ios - 显示通知的键盘不叫 iOS 12

ios - 使用 GCD 在后台创建 UIKit 对象是一种不好的做法吗?

swift - Swift 中具有多个可访问标签和图像的按钮