在UITextField中获取有理文本,可以通过以下方法实现:
import UIKit
let textField = UITextField(frame: CGRect(x: 50, y: 50, width: 200, height: 40))
textField.textColor = UIColor.black
textField.font = UIFont.systemFont(ofSize: 16)
textField.textAlignment = NSTextAlignment.center
class ViewController: UIViewController, UITextFieldDelegate {
// ...
}
textField.delegate = self
func textFieldDidBeginEditing(_ textField: UITextField) {
print("开始编辑")
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("结束编辑")
}
view.addSubview(textField)
let text = textField.text
完整代码示例:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let textField = UITextField(frame: CGRect(x: 50, y: 50, width: 200, height: 40))
textField.textColor = UIColor.black
textField.font = UIFont.systemFont(ofSize: 16)
textField.textAlignment = NSTextAlignment.center
textField.delegate = self
view.addSubview(textField)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
print("开始编辑")
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("结束编辑")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
在这个示例中,我们创建了一个UITextField实例,并设置了其位置和大小、文本颜色、字体大小和文本对齐方式。我们还实现了UITextFieldDelegate协议中的方法,以便在文本框开始和结束编辑时执行特定操作。最后,我们将UITextField添加到视图中,并使用text属性获取其中的文本内容。
领取专属 10元无门槛券
手把手带您无忧上云