gpt4 book ai didi

ios - Swift - addTarget() 不与 addSubview() 一起使用

转载 作者:行者123 更新时间:2023-11-28 23:34:17 25 4
gpt4 key购买 nike

我正在尝试添加一个从底部出现的横幅:

enter image description here

所以我创建了一个UIView,里面有一个UIButton。问题是当我点击按钮时,什么也没有发生。

@objc func myButtonAction() {
print("My Button tapped")
}

func notifBanner(message: String, color: UIColor, backgroundColor: UIColor, button: UIButton){

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let window = appDelegate.window!

if infoViewIsShowing == false{
infoViewIsShowing = true

let grey1 = UIColor(red: 196/255, green: 196/255, blue: 196/255, alpha: 1)

let infoViewHeight = CGFloat(50)
let infoViewY = window.bounds.height + infoViewHeight

let infoView = UIView(frame: CGRect(x: 10, y: infoViewY, width: window.bounds.width - 20, height: infoViewHeight))
infoView.backgroundColor = backgroundColor
infoView.layer.cornerRadius = 8
infoView.clipsToBounds = true

infoView.isUserInteractionEnabled = true
window.addSubview(infoView)


infoView.alpha = 0.4

let widthButton = CGFloat(115)
let goToProfileButton = UIButton()
goToProfileButton.frame = CGRect(x: 0, y: 0, width: infoLabelWidth, height: infoLabelHeight)
goToProfileButton.setTitle("View Profile", for: .normal)
goToProfileButton.tintColor = .white
goToProfileButton.addTarget(self, action: #selector(self.myButtonAction), for: .touchUpInside)
goToProfileButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)

infoView.addSubview(goToProfileButton)

// Animate bannerView
UIView.animate(withDuration: 0.4, animations: {

infoView.alpha = 1
infoView.frame.origin.y = window.bounds.height - infoViewHeight - 60

}, completion: { (finished: Bool) in
if finished{

UIView.animate(withDuration: 0.4, delay: 3, options: .curveEaseIn, animations: {
// move up
infoView.frame.origin.y = infoViewY
infoView.alpha = 0.3

}, completion: { (finished: Bool) in
if finished {
infoView.removeFromSuperview()
self.infoViewIsShowing = false
}
})

}
})
}
}

我尝试添加 infoView.isUserInteractionEnabled = true 但它仍然无法正常工作。您知道我如何在单击按钮时发送操作吗?

最佳答案

假设您希望能够在按钮出现的 3 秒内点击按钮,您可以尝试更改代码以使用 DispatchQueue asyncAfter

UIView.animate(withDuration: 0.4, animations: {
infoView.alpha = 1
infoView.frame.origin.y = window.bounds.height - infoViewHeight - 60
}, completion: { (finished: Bool) in
if finished{
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseIn, animations: {
// move up
infoView.frame.origin.y = infoViewY
infoView.alpha = 0.3
}, completion: { (finished: Bool) in
if finished {
infoView.removeFromSuperview()
self.infoViewIsShowing = false
}
})
}
}
})

关于ios - Swift - addTarget() 不与 addSubview() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55550849/

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