gpt4 book ai didi

ios - UIButton 上的 addTarget 不起作用

转载 作者:行者123 更新时间:2023-11-28 14:37:33 25 4
gpt4 key购买 nike

我有一个 UIView 类

class FloatingView  : UIView {
lazy var floatingButton : UIButton = {
let button = UIButton(type: UIButtonType.system)
button.setBackgroundImage(#imageLiteral(resourceName: "ic_add_circle_white_36pt"), for: .normal)
button.tintColor = UIColor().themePurple()
button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()

override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

func setupViews(){ addSubview(floatingButton) }

override func didMoveToWindow() {
super.didMoveToWindow()

floatingButton.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor).isActive = true
floatingButton.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor).isActive = true
floatingButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
floatingButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
}

@objc func buttonClicked (){
print("Clicked..")
}

添加此以查看

let floatingButton = FloatingView()
view.addSubview(floatingButton)

我还指定了 float View 的约束。

Screenshot of button

按钮已按预期添加到 View 中,但单击按钮时未调用“buttonClicked”函数。虽然单击时按钮上的淡入淡出动画有效。我已经尝试过 UITapGesture 但没有工作。

我已经更新类如下

class FloatingView{
lazy var floatingButton : UIButton = {
let button = UIButton(type: UIButtonType.system)
button.setBackgroundImage(#imageLiteral(resourceName: "ic_add_circle_white_36pt"), for: .normal)
button.tintColor = UIColor().themePurple()
button.addTarget(self, action: #selector(buttonClicked(_:)), for: UIControlEvents.touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()

private var view : UIView!

func add(onview: UIView ){
view = onview
configureSubViews()
}

private func configureSubViews(){
view.addSubview(floatingButton)
floatingButton.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor).isActive = true
floatingButton.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true
floatingButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
floatingButton.heightAnchor.constraint(equalToConstant: 60).isActive = true
}

@objc func buttonClicked(_ sender : UIButton){
print("Button Clicked")
}
}

在 Controller 中

let flButton = FloatingView()
flButton.add(onview: view)

我正在尝试创建一个 float 操作按钮 like this .我不确定我的做法是否正确。

最佳答案

试着把 Action 改成

Action :#selector(buttonClicked(_:))

和函数

@objc func buttonClicked(_ sender: UIButton){..}

关于ios - UIButton 上的 addTarget 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50759592/

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