【发布时间】:2020-07-28 17:05:24
【问题描述】:
美好的一天,
我想创建一个自定义警报以从用户那里收集信息。但是,它不会加载并使用以下代码崩溃:
xib 文件
import Foundation
import UIKit
class WorkoutAlert: UIView {
static let instance = WorkoutAlert()
@IBOutlet var parentView: UIView!
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBAction func workoutTextField(_ sender: UITextField) {
}
@IBAction func datePicker(_ sender: UIDatePicker) {
}
@IBAction func cancelButtonPressed(_ sender: UIButton) {
parentView.removeFromSuperview()
}
@IBAction func doneButtonPressed(_ sender: UIButton) {
}
override init(frame: CGRect) {
super.init(frame: frame)
Bundle.main.loadNibNamed("WorkoutAlert", owner: self, options: nil)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func commonInit () {
alertView.layer.cornerRadius = 10
parentView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
parentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
func showAlert(title: String) {
self.titleLabel.text = title
UIApplication.shared.keyWindow?.addSubview(parentView)
}
// MARK: - End of Code
}
使用 xib 的 ViewController 的相关代码:
class WorkoutViewController: UIViewController {
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
WorkoutAlert.instance.showAlert(title: "Add a new workout")
}
}
xib 的约束
非常感谢任何帮助。我是一个新手,已经找到了许多创建警报而不是使用标准警报控制器的方法和示例。
【问题讨论】:
-
你不应该打电话给
init(frame:)吗?您的警报没有大小?instance = WorkoutAlert()是instance = WorkoutAlert.init(), , 不是 init(frame:) -
你为什么要为
WorkoutAlert创建一个单例实例?为UIView设置一个单例似乎是一个非常糟糕的主意。此外,您应该实现init?(coder:)而不是从中抛出fatalError,因为您显然是在调用它。
标签: ios swift xib uialertview uialertcontroller