gpt4 book ai didi

ios - 如果在函数内部创建了一个按钮,那么添加它的正确位置在哪里,以便可以访问它?

转载 作者:行者123 更新时间:2023-11-28 12:39:36 34 4
gpt4 key购买 nike

func createButton() {
let b = UIButton()
// Some code to modify image of button
b.addTarget(self, action: "fade", forControlEvents: .TouchDown)
self.view.addSubview(b)
// Some code to add constraints
}

func fade() {
UIView.animeWithDuration(5, animations: {
self.b.alpha = 0 // Error (ViewController has no member 'b')
}

我收到这个错误是因为 createButton() 有一个独立于 ViewController 的 View 吗?因为我试过传入按钮,并使用 sender.view.b.alpha = 0,但是 UIButton 没有 view

谢谢。

最佳答案

您需要在正确的范围内声明按钮。目前您只在 createButton 的函数范围内声明它。但是你可以让它成为你的类的实例变量。然后您可以通过这两种方法访问它。

class XYZ
{

var button: UIButton?

func createButton() {
self.button = UIButton()
// Some code to modify image of button
self.button.addTarget(self, action: "fade", forControlEvents: .TouchDown)
self.view.addSubview(self.button)
// Some code to add constraints
}

func fade() {
UIView.animeWithDuration(5, animations: {
self.button.alpha = 0
}
}

还有 here是一篇关于 Swift 中对象的作用域和生命周期的文章。

希望这对您有所帮助。

关于ios - 如果在函数内部创建了一个按钮,那么添加它的正确位置在哪里,以便可以访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39774524/

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