我有文字字段。
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)
答案 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)
}
}
}
结果