Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
901 views
in Technique[技术] by (71.8m points)

swift - iOS Copy Paste phone from contacts to UITextField adds strange unicode characters

The simplified scenario is the following.

  • New project using Single View App template.
  • Add a UITextField to the ViewController.
  • Run the app and copy and paste a Contacts phone number [ej. John Appleseed one (888) 555-5512) ] to the UITextField.

The number will be added with a Unicode character at the beginning and at the end, getting like u{e2}(888) 555-5512u{e2} when exploring the variable while debugging.

This is really weird and in my opinion, not the intended behaviour. Is this a bug or something that works intentionally this way?

Code:

Nothing complicated here. As described before, brand new project, add UITextField, add Button, and if button triggered print the result. The print will show the phone just fine, just put a breakpoint in the print line and see the value of the phone var to see what I mean.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var phoneLabel: UITextField!

    @IBAction func goButton(_ sender: UIButton) {

        let text = phoneLabel.text ?? ""
        print(text)
    }
}

Tested in:

  • iOS 11.1 - iPhone X
  • Xcode 9.1

Steps with images:

enter image description here


enter image description here


This is what I got at the breakpoint line.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had exactly the same issue recently. Interestingly enough what you see in the debugger is unfortunately not what is actually pasted. If you copy the number to a different place and investigate it with your console for example you will get the following output:

>>> u"U+202D(888) 5555-5512U+202C"
u'u202d(888) 5555-5512u202c'
>>> name(u"U+202D")
'LEFT-TO-RIGHT OVERRIDE'
>>> name(u"U+202C")
'POP DIRECTIONAL FORMATTING'

So as you can see it is really two different invisible characters controlling the flow of the text.

In order to solve that I filtered out all unicode characters of the cF category. So you could do:

phoneLabel.text?.replacingOccurrences(of: "\p{Cf}", with: "", options: .regularExpression)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...