swift2 如何在Swift中通过图像视图创建自定义文本字段

uurity8g  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(164)

我尝试将键盘输入显示到框中(如图所示),并且仍然能够将输入作为一个来读取,而不是4个不同的输入。框是图像视图,我想将它们转换为一个文本字段。

0wi1tuuw

0wi1tuuw1#

您可以这样做:
1)创建UIView或UITableViewCell类:

class ConfirmTableViewCell: UITableViewCell {

   @IBOutlet weak var symbolsTextField: UITextField!
   @IBOutlet weak var firstLabel: UILabel!
   @IBOutlet weak var secondLabel: UILabel!
   @IBOutlet weak var thirdLabel: UILabel!
   @IBOutlet weak var fourthLabel: UILabel!

   var code: String = ""

   override func awakeFromNib() {
       super.awakeFromNib()

       symbolsTextField.delegate = self
       symbolsTextField.becomeFirstResponder()

       resetContent()
   }

   func resetContent() {
       firstLabel.text = nil
       secondLabel.text = nil
       thirdLabel.text = nil
       fourthLabel.text = nil
   }
}

2)添加xib或者你也可以在故事板中完成。添加UITextFieldUIView,文本颜色清晰。

3)添加扩展名:

extension ConfirmTableViewCell: UITextFieldDelegate {

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

       if range.location > 3 {
           textField.text?.removeLast()
       }

       setupLabels(character: string, range: range)

       return true
   }

   func setupLabels(character: String, range: NSRange) {
       if range.location > 3 {
           self.code.removeLast()
       }

       if range.length == 0 {
           self.code += character
       } else {
           self.code.removeLast()
       }

       var codeString: String = self.code

       if let symbol = codeString.first {
           firstLabel.text = String(symbol)
           codeString.removeFirst()
       } else {
           firstLabel.text = nil
       }

       if let symbol = codeString.first {
           secondLabel.text = String(symbol)
           codeString.removeFirst()
       } else {
           secondLabel.text = nil
       }

       if let symbol = codeString.first {
           thirdLabel.text = String(symbol)
           codeString.removeFirst()
       } else {
           thirdLabel.text = nil
       }

       if let symbol = codeString.first {
           fourthLabel.text = String(symbol)
       } else {
           fourthLabel.text = nil
       }
   }

}

相关问题