【问题标题】:Swift: Move UILabel up when keyboard appearsSwift:出现键盘时向上移动 UILabel
【发布时间】:2017-06-15 19:08:33
【问题描述】:

我不知道如何在键盘出现时向上移动 UILabel。

目前,当我使用 iPhone 7 进行模拟时,标签离顶部大约 140 像素,并且在键盘出现时完全居中。

但是,当使用较小的 iPhone 5 时,我遇到了这个问题。

键盘与 UILabel 重叠的位置。

我要做的是在键盘出现时将 UILabel 居中。

大多数教程都展示了如何将 UITextField 向上移动,但我尝试为 UILabel 应用相同的方面但失败了。

【问题讨论】:

  • 您尝试了哪些不起作用的方法?除了如何获得对对象的引用之外,移动UILabel 与移动UITextField 应该没有什么不同。也许展示你正在尝试的代码,并描述什么是“不工作”?
  • 您需要在滚动视图中显示该标签并更改偏移量以反映键盘的高度。

标签: ios iphone swift uilabel


【解决方案1】:

当键盘出现时向上移动控件的一种可能的解决方案是向控件添加底部约束并定义这些约束的出口。

 @IBOutlet weak var controlBottomConstraint: NSLayoutConstraint!

viewDidLoad注册一个keyboardWillShow方法,当键盘出现时接收通知如下:

NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

然后在keyboardWillShow 方法中更新约束(controlBottomConstraint),如下所示:

func keyboardWillShow(_ notification:Notification) {
  ...
    let userInfo:NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
    let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height
  // controlBottomConstraint outlet to the control you want to move up
  controlBottomConstraint.constant = keyboardHeight + 8
}

旋转设备时也可以使用。

【讨论】:

  • @daanyyaal 如果这个答案解决了你的问题,我很高兴你接受它。
  • 这个答案是最好的。我没有使用bottomConstraint,而是使用了topConstraint。但是,现在我需要弄清楚当键盘存在时如何根据不同的设备将 UILabel 居中。
【解决方案2】:

如果您要进行约束,只需将乘数更改为 0.5。如果您正在做框架,请将框架的 y 位置 (yourLabel.frame.origin.y) 设置为 self.view.frame.height / 2

【讨论】:

    【解决方案3】:

    试试这个:做一个扩展并添加通知观察者

    class ViewController: UIViewController {
       var keyboardOnScreen = false
    
        @IBOutlet weak var searchBar: UISearchBar!
        override func viewDidLoad() {
            super.viewDidLoad()
    
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardDidShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: .UIKeyboardDidHide, object: nil)
    
            searchBar.delegate = self
        }
    
    }
    extension ViewController: UISearchBarDelegate {
    
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            return true
        }
    
    
        func keyboardWillShow(_ notification: Notification) {
            if !keyboardOnScreen {
                view.frame.origin.y -= keyboardHeight(notification)        }
        }
    
        func keyboardWillHide(_ notification: Notification) {
            if keyboardOnScreen {
                view.frame.origin.y += keyboardHeight(notification)
            }
        }
    
        func keyboardDidShow(_ notification: Notification) {
            keyboardOnScreen = true
        }
    
        func keyboardDidHide(_ notification: Notification) {
            keyboardOnScreen = false
        }
    
        private func keyboardHeight(_ notification: Notification) -> CGFloat {
            let userInfo = (notification as NSNotification).userInfo
            let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
            return keyboardSize.cgRectValue.height
        }
    
        private func resignIfFirstResponder(_ textField: UITextField) {
            if textField.isFirstResponder {
                textField.resignFirstResponder()
            }
        }
    
        @IBAction func userDidTapView(_ sender: AnyObject) {
            resignIfFirstResponder(textField)
        }
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            self.view.endEditing(true)
        }
    
    }
    

    【讨论】:

      【解决方案4】:

      第一个 ViewController

        import UIKit
      
          class ViewController: UIViewController , UITableViewDelegate ,UITableViewDataSource, UITextViewDelegate {
      
              @IBOutlet weak var ViewSend: UIView!
              @IBOutlet weak var txtMessage: UITextView!
              @IBOutlet weak var ChatTable: UITableView!
              var chatArray:[String] = []
                var collect:String!
              override func viewDidLoad()
              {
                  super.viewDidLoad()
                  txtMessage.delegate = self
                 NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
                 NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
                 print(self.ViewSend.frame.origin.y)
      
              }
              override func didReceiveMemoryWarning()
              {
                  super.didReceiveMemoryWarning()
              }
              func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
              {
                  return chatArray.count
              }
              func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                  let cell = tableView.dequeueReusableCell(withIdentifier: "CellDemo") as! chatlableTableViewCell
                  let obj = chatArray[indexPath.row]
                  cell.lblchat.text = obj
                  cell.lblchat.sizeToFit()
                  cell.lblchat.layer.cornerRadius = 2
                  cell.lblchat.clipsToBounds = true
                  return cell
              }
      
      
              @IBAction func btnSendPresssed(_ sender: UIButton)
              {
                      if txtMessage.text == ""
                      {
      
                      }
                      else
                      {
      
                          collect =  txtMessage.text
                          chatArray.append(collect)
                      }
                  ChatTable.reloadData()
                  txtMessage.text = ""
              }
              func calcheight(strin:String) -> CGFloat
              {
                  let label =  UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: CGFloat.greatestFiniteMagnitude))
                  label.numberOfLines = 0
                  label.text = strin
                  label.sizeToFit()
                  return label.frame.height + 2
      
              }
              func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
              {
                  let height = self.calcheight(strin: String(describing: chatArray[indexPath.row]))
                  return height
      
              }
              func keyboardWillShow(notification: NSNotification) {
      
                  if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
                  {
                      if self.ViewSend.frame.origin.y != keyboardSize.height
                      {
                          self.ViewSend.frame.origin.y -= keyboardSize.height
                          self.ChatTable.frame.size.height -= keyboardSize.height
                      }
                 }
              }
              func keyboardWillHide(notification: NSNotification)
              {
      
                 if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
                 {
                      self.ViewSend.frame.origin.y += keyboardSize.height
                  self.ChatTable.frame.size.height += (keyboardSize.height + ViewSend.frame.size.height)
      
                 }   
      
              }
      
          }
      

      表格视图单元格

      import UIKit
      
      class chatlableTableViewCell: UITableViewCell {
      
          @IBOutlet weak var lblchat: UILabel!
          override func awakeFromNib() {
              super.awakeFromNib()
              // Initialization code
          }
      
          override func setSelected(_ selected: Bool, animated: Bool) {
              super.setSelected(selected, animated: animated)
      
              // Configure the view for the selected state
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-15
        相关资源
        最近更新 更多