gpt4 book ai didi

ios - 在不同的类swift中以编程方式创建一个按钮

转载 作者:行者123 更新时间:2023-12-01 18:42:05 28 4
gpt4 key购买 nike

我是 swift 新手,并尝试以编程方式创建 UIButton。我有两个类。我正在一个类中创建一个按钮并从另一个类中调用该方法。

类 View Controller

import UIKit

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let renderobj = render()
renderobj.sign()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

类渲染
import UIKit

class render: UIViewController {
func sign() {
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

self.view.addSubview(button)
}

func buttonAction(sender: UIButton!) {
print("Button tapped")
}
}

但是没有创建按钮。如果我把 UIButton内码 viewDidLoad() , 有用。我希望在不同类的函数中创建按钮。有可能这样做吗?

谢谢你的帮助

最佳答案

func sign() -> UIButton
{
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
return button
}

After returning that button you can add it in your calling view controller view


override func viewDidLoad() {
super.viewDidLoad()

let renderobj = render()
let button = renderobj.sign()
self.view.addSubview(button)
}

关于ios - 在不同的类swift中以编程方式创建一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41460571/

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