我创建了一些自定义UIViews,并在我的项目中的另一个UIView中实现。 我在调用某些函数或为某些对象设置值时遇到崩溃但在设置属性时没有崩溃。 请参阅以下代码以正确理解代码和问题。
class SearchProfileDetailView: UIView {
@IBOutlet weak var userInfoTable: UITableView!
var userObject: UserObject?
override init(frame:CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib()
}
func loadViewFromNib() {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "SearchProfileDetailView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
self.addSubview(view);
}
func setColor() {
self.backgroundColor = UIColor.red
}
}
我已经在另一个UIView中使用了这个 SearchProfileDetailView ,其中包含接口构建器和分配的插座,请参阅下面的代码。
class SearchResultView: UIView {
@IBOutlet weak var profileDetailView: SearchProfileDetailView!
var currentIndex: Int?
override init(frame:CGRect) {
super.init(frame: frame)
loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadViewFromNib()
}
func loadViewFromNib() {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "SearchResultView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
view.frame = bounds
self.addSubview(view);
}
func setUserProfile(userObject: UserObject) {
profileDetailView.backgroundColor = UIColor.red // Not Crashed
profileDetailView.userObject = userObject //Crashed with error mentioned in title of question
profileDetailView.setColor() ////Crashed with error mentioned in title of question
}
}
调用profileDetailView.setColor()时崩溃了 profileDetailView.userObject = userObject但没有崩溃 profileDetailView.backgroundColor = UIColor.red
现在我已将此 SearchResultView 与界面构建器一起用于UIViewController。
class ExploreViewController: UIViewController {
@IBOutlet weak var searchResultView: SearchResultView!
func getResult() {
SearchAPIHandler().search(params: parameters) {[weak self] (responseData) in
DispatchQueue.main.async {
guard let strongSelf = self else {
return
}
if let users = responseData.users, !users.isEmpty {
strongSelf.searchResultView.setUserProfile(userObject: users[0])
}
}
}
}