gpt4 book ai didi

swift - Prog 从类中创建的按钮不会出现 - Swift IOS

转载 作者:行者123 更新时间:2023-11-30 13:04:13 24 4
gpt4 key购买 nike

我正在尝试根据数组的大小自动将许多 customClass 按钮添加到我的 View 中。

创建了类并在类中调用了适当的方法,但没有显示任何内容。调试告诉我该方法按预期调用/执行(3x)。

当我将函数直接添加到 View Controller 时,它确实可以工作。

我在这里缺少什么???

ViewController代码:

import UIKit

class ViewController: UIViewController {

let userArray: [String] = ["One","Two","Three"]

override func viewDidLoad() {
super.viewDidLoad()

for item in userArray {
CustomCheckBox().showNewButton()
}
}

.. Other stuff...
}

自定义按钮类代码:

{
import UIKit

class CustomCheckBox: UIButton {

let checkedImage: UIImage = UIImage(named:"chckbox_on")!
let uncheckedImage: UIImage = UIImage(named: "chckbox_off")!
var newButton: CustomCheckBox!

..... other functions (isChecked, buttonClicked, ..)

func showNewButton (){
newButton = CustomCheckBox (type: UIButtonType.Custom)
newButton.bounds = CGRect(x: 0, y: 0, width: 45, height: 45)
newButton.center = CGPoint(x: 40, y: 40)
newButton.addTarget(newButton, action: #selector(CustomCheckBox.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
newButton.isChecked=false
self.addSubview(newButton)
}
}

最佳答案

可以考虑像这样重组你的代码

class CustomCheckBoxContainer: UIView {
var newButton: CustomCheckBox!


func showNewButton (){
newButton = CustomCheckBox (type: UIButtonType.custom)
newButton.bounds = CGRect(x: 0, y: 0, width: 45, height: 45)
newButton.center = CGPoint(x: 40, y: 40)
newButton.addTarget(newButton, action: #selector(CustomCheckBox.buttonClicked(_:)), for: UIControlEvents.TouchUpInside)
newButton.isChecked=false
self.addSubview(newButton)
}



}

class CustomCheckBox: UIButton {
let checkedImage: UIImage = UIImage(named:"chckbox_on")!
let uncheckedImage: UIImage = UIImage(named: "chckbox_off")!

//add here all your button functionality
}

然后将您的 View 确实加载为如下所示:

override func viewDidLoad() {
super.viewDidLoad()

for item in userArray {
let customCheckBoxContainer = CustomCheckBoxContainer()
customCheckBoxContainer.showNewButton()
self.view.addSubview(customCheckBoxContainer)
}
}

关于swift - Prog 从类中创建的按钮不会出现 - Swift IOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39572179/

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