swift - Toast UILabel 出现在屏幕外,尽管我正确设置了 y

标签 swift uitableview uilabel

我在 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/

相关文章:

ios - UiView 固定在 UiTableViewController 之上

objective-c - Swift - Objective-C 加载类方法?

iOS 11 UITableView isEditing 标志设置不正确

ios - 如何从完成 block 安全地推送 View Controller ?

ios - 调整 UITableViewCell 内的 UILabel 以适应内容

ios - Swift ScrollView 和键盘问题

ios - 神秘的_UIParallaxDimmingView。它是什么?

ios - UILabel.attributedText 设置属性一次,然后只更改文本(字符串)

iphone - 如何在同一标签上使用不同颜色

swift - 创建 WAV 文件时生成错误字节