【发布时间】:2018-11-09 17:40:51
【问题描述】:
我正在尝试制作自定义警报视图,但由于显示的视图正在切割视图的下半部分这一事实,我面临一些问题(下图)
显示方式:
期望的输出:
所以基本上,我有一个名为 CustomAlertView 的 XIB,由一个带有 init 的同名类支持,如下所示:
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("CustomAlertView", owner: self, options: nil)
contentView.frame = self.bounds
contentView.translatesAutoresizingMaskIntoConstraints = true
addSubview(contentView)
//contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
我有另一个类负责使用 customAlertView 创建警报 CustomAlert。这个 CustomAlert 类正在使用以下代码创建 backgroundView 和 dialogView(我正在尝试将我的 customAlertView 添加到其中):
func initialize(title:String, description:String){
dialogView.clipsToBounds = true
backgroundView.frame = frame
backgroundView.backgroundColor = UIColor.black
backgroundView.alpha = 0.6
backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTappedOnBackgroundView)))
addSubview(backgroundView)
dialogView.frame.origin = CGPoint(x: 0, y: 0)
dialogView.frame.size = CGSize(width: frame.width-32, height: frame.height/3)
dialogView.backgroundColor = UIColor.white
dialogView.layer.cornerRadius = 6
let alertView = CustomAlertView.init(frame: self.bounds)
alertView.titleLabel.text = title
alertView.descriptionLabel.text = description
alertView.cancelButton.backgroundColor = UIColor.brown
dialogView.addSubview(alertView)
addSubview(dialogView)
}
我认为我对框架和边界感到困惑,但找不到解决方案。
我希望将所需的输出完美地放置在 dialogView 中。
编辑
CustomAlert 中我的 .show 函数的代码
func show(animated:Bool){
self.backgroundView.alpha = 0
self.dialogView.center = CGPoint(x: self.center.x, y: self.frame.height + self.dialogView.frame.height/2)
UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(self)
if animated {
UIView.animate(withDuration: 0.33, animations: {
self.backgroundView.alpha = 0.66
})
UIView.animate(withDuration: 0.33, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: {
self.dialogView.center = self.center
}, completion: { (completed) in
})
}else{
self.backgroundView.alpha = 0.66
self.dialogView.center = self.center
}
}
Github 链接git-alert-view
【问题讨论】:
-
为什么不使用自动布局在视图控制器中添加警报?
-
我不确定您在视图控制器中使用自动布局是什么意思。在我的视图控制器中,我只是创建了传递标题和描述的警报,以及一个 .show(将 dialogView 设置为中心)
-
能否请您添加您的 show() 方法的代码?
-
在您的初始化方法中,您不会像在第一个代码块中显示的那样初始化 CustomAlertView。我认为你应该通过 nib 加载它。
-
我编辑了第一个块代码,我想现在更清楚了,抱歉混淆了....我实际上在 init 中加载了 nib
标签: ios swift uiview autolayout xib