gpt4 book ai didi

ios - 试图给UIButton一个特殊的属性

转载 作者:行者123 更新时间:2023-12-01 22:03:41 25 4
gpt4 key购买 nike

我需要UIButton具有属性bookId。我尝试了以下代码,但给了我错误Property 'self.bookId' not initialized at super.init call。我需要该属性,以便能够在单击按钮时在数据库中查询该特定的bookId。

import UIKit

class BookUIButton: UIButton {
var bookId: String

init(frame: CGRect, bookId: String) {
super.init(frame: frame);
self.bookId = bookId
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override init(frame: CGRect) {
super.init(frame: frame)
}

override func awakeFromNib() {
super.awakeFromNib()

//TODO: Code for our button
}
}

任何帮助将不胜感激!!!

最佳答案

swift强制您在每个成员var可能被使用之前初始化它。由于无法确定超速转弯时会发生什么,因此会出错:安全比后悔好!

解决方案1:

class BookUIButton: UIButton {
var bookId: String?

init(frame: CGRect, bookId: String) {
super.init(frame: frame);
self.bookId = bookId
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override init(frame: CGRect) {
super.init(frame: frame)
}

override func awakeFromNib() {
super.awakeFromNib()

//TODO: Code for our button
}
}

解决方案2:
有一种更好的方法来跳过此错误。因此,您要做的就是在声明后初始化成员:
class BookUIButton: UIButton {
var bookId: String = String()

init(frame: CGRect, bookId: String) {
super.init(frame: frame);
self.bookId = bookId
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

override init(frame: CGRect) {
super.init(frame: frame)
}

override func awakeFromNib() {
super.awakeFromNib()

//TODO: Code for our button
}
}

关于ios - 试图给UIButton一个特殊的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60008926/

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