我已经以编程方式创建了一组按钮,但是当我从外部类触发按钮触发视图上的函数时,所有当前变量引用都在我的视图中消失并导致错误,表示存在意外的可选项。任何静态数据和逻辑仍可正常加载。如果我检查选项,程序会停止错误,因此由于某种原因删除了引用。我的构建按钮的类
class CategoryButton: NSObject{
func createButton(category: Category, index: Int) -> CategoryButton.Button{
let button = CategoryButton.Button(frame: .zero, category: category)
button.titleEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
button.setTitle(category.name, forState: .Normal)
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button.titleLabel?.font = UIFont(name: "Helvetica-bold", size: 17.0)
button.titleLabel?.numberOfLines = 2
button.titleLabel?.textAlignment = .Center
button.setBackgroundImage(UIImage(named: "category-box.png"), forState: .Normal)
button.frame = CGRectMake(CGFloat(index * (130 + 8)), 15 , 130, 106)
button.addTarget(button, action: #selector(button.categoryClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
return button
}
class Button: UIButton{
var category: Category?
init(frame: CGRect, category: Category) {
self.category = category
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func categoryClicked(sender: CategoryButton.Button){
if let c = sender.category{
Workstation.instance.currentCategory = c
let dashboard = DashboardViewController()
dashboard.loadCategories()
}
}
}
class var instance: CategoryButton{
struct Static {
static let instance = CategoryButton()
}
return Static.instance
}
}
在我的视图中,我正在调用使用
创建按钮func loadCategories(){
var currentCategoryButtons: [CategoryButton.Button] = []
var addedCount = 0
for category in Workstation.instance.categories{
if let currentCategory = Workstation.instance.currentCategory{
print("\(currentCategory.name) \(category.name)")
print("\(currentCategory.id) \(category.parentCategoryId)")
if currentCategory.id == category.parentCategoryId{
let button = CategoryButton.instance.createButton(category, index: addedCount)
if let container = self.categoryContainer{
currentCategoryButtons.append(button)
container.addSubview(button)
addedCount += 1
}
}
}else{
if category.parentCategoryId.characters.count <= 0{
let button: CategoryButton.Button = CategoryButton.instance.createButton(category, index: addedCount)
currentCategoryButtons.append(button)
self.categoryContainer.addSubview(button)
addedCount += 1
}
}
}
if let container = self.categoryContainer{
container.contentSize = CGSizeMake(CGFloat(addedCount * (130 + 8)), 131)
container.contentInset = UIEdgeInsetsMake(0, 20, 0, 0)
container.setContentOffset(CGPoint(x: -15, y: 0), animated: true)
}
}