如何将后续文本添加到uitextfield

时间:2017-08-14 05:31:20

标签: ios swift uitextfield

我有一个带有占位符的文本字段,名为letschat。现在每当我开始输入文本字段时,我想将我的文本字段显示为some @letschat。当我的文本字段为空时,我的占位符必须显示。我做了。但是每当我开始输入我的文本字段时,我想设置。无论我输入什么,我希望这个文本也可见:

  

一些@Lletchat

我该怎么做?

5 个答案:

答案 0 :(得分:0)

使您的班级符合UITextfieldDelegate,然后指定textfield.delegate = self

现在,添加此委托方法,如果您希望在用户端分类后附加@letschat。

func textFieldDidEndEditing(textField: UITextField) {
    textField.text = "\(textField.text)@letschat"
}

或者如果您想在打字时间使用它。

textField.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

func textFieldDidChange(textField: UITextField) {
    if textField.containsString("@letschat")  {
        textField.text = textField.text.stringByReplacingOccurrencesOfString("@letschat", withString: "")
    }

    textField.text = "\(textField.text)@letschat"

}

希望这有帮助。

答案 1 :(得分:0)

您可以使用UITextField textFieldDidChange的{​​{3}},并在每次textField文本更改时接听电话。

就像那样:

func textChangedAction(sender:UITextFiled) {
   if sender.text.rangeOfString("@Lletschat") != nil{ 
       sender.text = sender.text.replacingOccurrences(of: "@Lletschat", with: "")  
   }
   sender.text = "\(sender.text!) @Lletschat"
}

如果您想更改特定文字的颜色,可以查看action

答案 2 :(得分:0)

像这样实现textfield委托 -

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    textField.text = textField.text?.replacingOccurrences(of: " @\(textField.placeholder!)", with: "", options: .literal, range: nil)
    textField.text?.append(string)
    textField.text?.append(" @\(textField.placeholder!)")

    return false
}

答案 3 :(得分:0)

简单的解决方案:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let newRange = textField.text?.range(from: range), let result = textField.text?.replacingCharacters(in: newRange, with: string) else { return true }
    if result.endsWithString("@letschat") {
        return true
    } else {
        textField.text = result + "@letschat"
        let position = textField.position(from: textField.beginningOfDocument, offset: result.characters.count)!
        textField.selectedTextRange = textField.textRange(from: position, to: position)
        return false
    }
}

使用帮助程序扩展名:

extension String {

    func range(from oldOne: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: oldOne.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(utf16.startIndex, offsetBy: oldOne.location + oldOne.length, limitedBy: utf16.endIndex),
            let from = from16.samePosition(in: self),
            let to = to16.samePosition(in: self)
            else { return nil }
        return from ..< to
    }

    func endsWithString(_ string: String) -> Bool {
        guard characters.count >= string.characters.count else { return false }
        let index = self.index(startIndex, offsetBy: characters.count - string.characters.count)
        let substring = self.substring(from: index)
        return substring == string
    }
}

困难但明确的解决方案是创建自己的UIControl - 子类,其中包含UITextFieldUILabel子视图:

+-----------+         +-----------+
| textfield | -(3px)- | @letschat |
+-----------+         +-----------+

使用autolayout保持它之间的3个像素的距离。 不要忘记将您的类配置为将所有传入的操作发送到文本字段。您可以为这些控件使用不同的字体颜色,这样用户就不会对更改标签值的工作感到困惑。

答案 4 :(得分:0)

我创建了一个UITextField子类,它使用占位符(如果设置)作为后缀。据我所知,一切都按预期工作。也许需要进行一些调整以满足您的需求。

随意询问是否有任何不清楚的地方:

class SuffixTextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }

    private func sharedInit() {
        addTarget(self, action: #selector(textChanged), for: .editingChanged)
    }

    override var text: String? {
        didSet {
            selectedTextRange = maxTextRange
        }
    }

    override var attributedText: NSAttributedString? {
        didSet {
            selectedTextRange = maxTextRange
        }
    }

    @objc private func textChanged() {
        if let currentText = text, let placeholder = placeholder {
            if currentText == placeholder {
                self.text = nil
            } else if !currentText.hasSuffix(placeholder) {
                self.text = currentText + placeholder
            }
        }
    }

    private var maxCursorPosition: UITextPosition? {
        guard let placeholder = placeholder, !placeholder.isEmpty else { return nil }
        guard let text = text, !text.isEmpty else { return nil }
        return position(from: beginningOfDocument, offset: (text as NSString).range(of: placeholder, options: .backwards).location)
    }

    private var maxTextRange: UITextRange? {
        guard let maxCursorPosition = maxCursorPosition else { return nil }
        return textRange(from: maxCursorPosition, to: maxCursorPosition)
    }

    override var selectedTextRange: UITextRange? {
        get { return super.selectedTextRange }
        set {
            guard let newRange = newValue,
                let maxCursorPosition = maxCursorPosition else {
                    super.selectedTextRange = newValue
                    return
            }

            if compare(maxCursorPosition, to: newRange.start) == .orderedAscending {
                super.selectedTextRange = textRange(from: maxCursorPosition, to: maxCursorPosition)
            } else if compare(maxCursorPosition, to: newRange.end) == .orderedAscending {
                super.selectedTextRange = textRange(from: newRange.start, to: maxCursorPosition)
            } else {
                super.selectedTextRange = newValue
            }
        }
    }

}

在这里你可以看到预览: https://www.dropbox.com/s/etkbme37wuxbw1q/preview.mov?dl=0