限制输入字段中的字符

时间:2015-03-16 11:34:26

标签: xcode swift

如何限制用户可以放入文本字​​段的字符数量? 我的代码到现在为止如下:

@IBAction func findBudget(sender: AnyObject) {

    var enteredBudget = enterBudget.text.toInt()

    if enteredBudget != nil {

我是一个快速的初学者,这意味着如果你能给我一个非常精确的答案,我会很高兴:)

2 个答案:

答案 0 :(得分:0)

以下是您的代码:

如果您想使用TextField

import UIKit
// Add your UITextFieldDelegate Here
class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var userText: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    // Here assign delegate to self
    self.userText.delegate = self
}

//Use this delegate function
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{

    var newLength:Int = (userText.text as NSString).length + (string as NSString).length - range.length
    var remainingChar1:Int = 5 - newLength

    return (newLength > 5) ? false : true
    }
}

在此delegate函数中,我将限制设置为5,因此用户只能在textFied中输入5个字符。您可以根据需要进行设置。

如果您想使用textView:

import UIKit

class ViewController: UIViewController, UITextViewDelegate {


@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.textView.delegate = self
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool{

    var newLength:Int = (textView.text as NSString).length + (text as NSString).length - range.length
    var remainingChar:Int = 5 - newLength
    return (newLength > 5) ? false : true
    }
}

希望这会对你有所帮助。

答案 1 :(得分:0)

您应该将textField的委托设置为查看控制器并添加:

extension ViewController: UITextFieldDelegate{
   func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
      let charsLimit = 5
      return (countElements(textField.text) - range.length + countElements(string) < charsLimit)
}

您也可以将Keyboard type设置为&#34;数字键盘&#34;在Interface Builder中,如果您只想要数字: enter image description here