我在 ViewController 上有一个 Toast 扩展,它继承了 class ViewControllerList: UITableViewController, UIPopoverPresentationControllerDelegate {
一切都很好,除了当我这样做的时候
extension UIViewController {
func showToast(message : String) {
let height = UIScreen.main.bounds.height
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: height-100, width: 150, height: 35))
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = .center;
toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
}
toast 总是出现在屏幕外 .. 在一个长的 uitableview 中 .. 无论我如何设置 y
它总是根据文档来思考.. 我已经调试了它并且 y= 676
但它似乎位于距离最后一个单元格内的 tableView 底部约 900 ...100 处
这是为什么,我该如何解决?
请不要记下来 - 尝试给出答案
最佳答案
不要添加到 self.view
,而是将 toast 标签添加为窗口的 subview :
extension UIViewController {
func showToast(message : String) {
let window = (UIApplication.shared.delegate as! AppDelegate).window
let height = window.bounds.height
let toastLabel = UILabel(frame: CGRect(x: window.bounds.width/2 - 75, y: height-100, width: 150, height: 35))
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = .center;
toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
// notice the change here
window.addSubview(toastLabel)
UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
}
这避免了当父 View 是 ScrollView 时你必须处理的问题。
关于swift - Toast UILabel 出现在屏幕外,尽管我正确设置了 y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55649531/