Floating TextField 浮動輸入框


加入協定

class ViewController: UIViewController, UITextFieldDelegate {

宣告資料

var tfv = UIView()
var tf = UITextField()
var keyheight = CGFloat()
let WIDTH = UIScreen.main.bounds.size.width
let HEIGHT = UIScreen.main.bounds.size.height

viewDidLoad

let notify = NotificationCenter.default
    notify.addObserver(self,
                       selector: #selector(showkeyboard),
                       name: NSNotification.Name.UIKeyboardWillShow,
                       object: nil)                       
    tfv.frame = CGRect(x: 0,
                     y: HEIGHT - 50,
                     width: WIDTH,
                     height: 50)
    tfv.backgroundColor = UIColor(red: 0,
                                green: 0,
                                blue: 0,
                                alpha: 0.5)
    tfv.layer.shadowColor = UIColor.black.cgColor
    tfv.layer.shadowOpacity = 0.3
view.addSubview(tfv)

    tf.frame = CGRect(x: 5,
                      y: 5,
                      width: WIDTH - 10,
                      height: 40)
    tf.delegate = self
    tf.backgroundColor = .white
    tf.textColor = .black
    tf.layer.cornerRadius = 10
    tf.layer.borderWidth = 2
    tf.layer.borderColor = UIColor.lightGray.cgColor
    tf.returnKeyType = .done
    tf.leftView = UIView(frame: CGRect(x: 0,
                                       y: 0,
                                       width: 10,
                                       height: 0))
    tf.leftViewMode = .always
    tf.addTarget(self,
                 action: #selector(hidekeyboard),
                 for: .editingDidEndOnExit)
tfv.addSubview(tf)

鍵盤顯示動作

func showkeyboard(aNotification: NSNotification) {

    let info: NSDictionary = aNotification.userInfo! as NSDictionary
    let value = info.object(forKey: UIKeyboardFrameEndUserInfoKey)
    let keyboard = (value as AnyObject).cgRectValue

    keyheight = (keyboard?.size.height)!

    tfv.frame.origin.y = HEIGHT - keyheight - 50
}

鍵盤關閉動作

func hidekeyboard(sender: UITextField) {
    UIView.animate(withDuration: 0.3,
                   delay: 0,
                   options: [.curveEaseInOut],
                   animations: { () -> Void in
                        self.tfv.frame.origin.y = self.HEIGHT - 50
                        self.view.endEditing(true)
                    },
                   completion: nil)
}

下載完整範例 OneDrive

results matching ""

    No results matching ""