【问题标题】:AddTarget connected to UIButton in customView does not work. (swift5, iOS)在自定义视图中连接到 UIButton 的 AddTarget 不起作用。 (斯威夫特 5,iOS)
【发布时间】:2020-10-28 06:52:27
【问题描述】:

有一个带有 UIButton 的自定义 UIView。 viewController 尝试通过 addTarget(...) 将该函数连接到该 UIButton。但它不起作用。

class customView: UIView {
     var button: UIButton = {
        //some properties
     }()
}
class viewController: UIViewController {
     var cv = customView()
     override func viewDidLoad() {
         cv.button.addTarget(self, action: #selector(someFunction), for: .touchUpInside)
     }
     @objc func someFunction() {
          print("Some function!")
     }
}

这段代码不是我写的。但这是我正在编写的代码的非常简短的表示。触摸按钮时 SomeFunction 不起作用。还需要什么?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    在简化的示例代码中很难找出实际问题,因为它本身并没有运行。 addTarget 本身的使用很好,所以我想问题出在代码的某个地方,我们在这里看不到。

    有根据的猜测是自定义视图的大小/布局存在问题。根据视图的不同,视图的边界可能会小于按钮或为零,尽管您仍会看到完整的按钮,但您无法单击它。如果您在单击按钮时没有在按钮上获得任何颜色效果,您可能会在标准按钮上注意到这一点。

    另一个好的下一步是查看 Xcode 的视图调试器,看看视图大小是否有问题。

    作为参考,我对您的示例代码进行了一些编辑,以使其在 Playground 中运行,并且您的函数在那里被很好地触发。

    import PlaygroundSupport
    import UIKit
    
    class CustomView: UIView {
        var button = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 20.0))
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            button.backgroundColor = .blue
            button.setTitle("click me", for: .normal)
            addSubview(button)
            button.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
            button.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    class ViewController: UIViewController {
        var customView = CustomView()
    
        override func viewDidLoad() {
            customView.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(customView)
    
            customView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
            customView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    
            customView.button.addTarget(self, action: #selector(someFunction), for: .touchUpInside)
        }
    
        @objc func someFunction() {
            print("Some function!")
        }
    }
    
    PlaygroundPage.current.liveView = ViewController()
    

    【讨论】:

    • 感谢您的友好回复。我想我在尝试简要解释时过多地减少了源代码。但你的解释让我知道该尝试什么。我为我糟糕的英语水平感到抱歉。这是翻译者写的一句话。
    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 2017-03-24
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多