如何移动文本域?

时间:2018-02-11 12:37:23

标签: ios swift uitextfield

我有文字字段。

let textFld = UITextField(frame: CGRect(x: 250, y: 
100, width: 200, height: 40))
textFld.placeholder = "Enter text here"
textFld.font = UIFont.systemFont(ofSize: 15)
textFld.borderStyle = UITextBorderStyle.roundedRect
textFld.autocorrectionType = UITextAutocorrectionType.no
textFld.keyboardType = UIKeyboardType.default
textFld.returnKeyType = UIReturnKeyType.done
textFld.clearButtonMode = UITextFieldViewMode.whileEditing;
textFld.contentVerticalAlignment = UIControlContentVerticalAlignment.center

self.view.addSubview(textFld)

我想用手指在屏幕上移动文本字段。我需要做什么? Error

Bug

1 个答案:

答案 0 :(得分:2)

使用平移手势识别器,你可以在我自己的答案中解决这个问题,我进一步解释Drag UIButton without it shifting to center [Swift 3]

此代码应该适合您

import UIKit

class DraggableUITextFieldViewController: UIViewController {

        @IBOutlet weak var textField: UITextField!

        var textFieldOrigin : CGPoint = CGPoint(x: 0, y: 0)
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            let gesture = UIPanGestureRecognizer(target: self, action: #selector(textFieldDrag(pan:)))
            self.textField.addGestureRecognizer(gesture)

            self.textField.layer.borderWidth = 1
            self.textField.layer.borderColor = UIColor.red.cgColor
        }

        @objc func textFieldDrag(pan: UIPanGestureRecognizer) {
            print("Being Dragged")
            if pan.state == .began {
                print("panIF")
                textFieldOrigin = pan.location(in: textField)
            }else {
                print("panELSE")
                let location = pan.location(in: view) // get pan location
                textField.frame.origin = CGPoint(x: location.x - textFieldOrigin.x, y: location.y - textFieldOrigin.y)
            }
        }
}

结果

enter image description here