【发布时间】:2021-12-26 07:27:46
【问题描述】:
我正在务实地创建一个 toast 视图(使用 SO 的一些帮助)并对其设置垂直约束。当我尝试在约束中使用动态值时,应用程序崩溃并显示以下消息:
Unable to parse constraint format:
Expected a ')' at the end of a constraint modifier, or a ',' before another constraint modifier
V:|-(>=66.0-[toastView(==40)]-68-|
^
吐司代码:
func showToastWithMessage(_ message : String, _ bottomBarHeight: CGFloat?) {
guard let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window else {
return
}
if let toast = window.subviews.first(where: { $0 is UILabel && $0.tag == -1001 }) {
toast.removeFromSuperview()
}
let toastView = UILabel()
toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
toastView.textColor = UIColor.white
toastView.textAlignment = .center
toastView.font = UIFont.systemFont(ofSize: 14.0, weight: .medium)
toastView.text = message
toastView.numberOfLines = 0
toastView.alpha = 0
toastView.translatesAutoresizingMaskIntoConstraints = false
toastView.tag = -1001
window.addSubview(toastView)
let horizontalCenterContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)
let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: (self.frame.size.width-25) )
var bannerPlacement = 300.0
if let height = bottomBarHeight {
bannerPlacement = height + 10.0
}
let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=\(bannerPlacement)-[toastView(==40)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["toastView": toastView])
NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
NSLayoutConstraint.activate(verticalContraint)
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
toastView.alpha = 1
}, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3), execute: {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
toastView.alpha = 0
}, completion: { finished in
toastView.removeFromSuperview()
})
})
}
应用程序在“V:|-(>=(bannerPlacement)-[toastView(==40)]-68-|”上崩溃,原因是创建verticalConstraint对象时(bannerPlacement)。如果我在那里放一个静态值,一切正常,但在我的情况下,值是动态的。如何在其中添加变量?
提前致谢!
【问题讨论】:
-
我冒昧地正确格式化了错误消息,它揭示了有关问题的其他信息。