修剪字符不适用于iOS 10.3 Xcode8.3

时间:2017-04-03 06:35:48

标签: ios swift string xcode8 ios10.3

请帮助我,我使用Xcode 8.3(swift 3.1),函数trimmingCharacters不起作用。我的代码如下:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}

文本字段中的输入为409 huỳnh,打印结果为409 huỳnh ,与预期不符:409huỳnh

6 个答案:

答案 0 :(得分:6)

来自文档:

  

从两端删除由set中包含的接收者字符构成的新字符串。

删除字符串中的字符。

您可以使用正则表达式替换字符串中的空格(对应于GenericRepository字符集):

.whitespaces

答案 1 :(得分:1)

trimmingCharacters仅删除前导和尾随空格。

试试这个

let _searchStr = searchStr.replacingOccurrences(" ", withString: "", options:.literal, range: nil)

答案 2 :(得分:0)

您可以使用

let trimmedString = searchStr.stringByReplacingOccurrencesOfString(" ", withString: "")

希望这能帮到你!

答案 3 :(得分:0)

Swift 3 中,您可以使用以下代码来解决问题

let _searchStr = searchStr.replacingOccurrences(of: " ", with: "")

答案 4 :(得分:0)

Swift 4 替代

因为Swift 4字符串再次是序列。您可以使用过滤器来完成此操作。

let _searchStr = searchStr.filter({ " ".contains($0) == false })

答案 5 :(得分:0)

您可以使用Swift 5字符属性isWhitespace并从字符串中过滤所有非空格:

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, "https://b2b.chiemsee.com/customer/account/login/");
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true); // to allow redirections
//curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, FALSE); // to avoid error
curl_setopt($ch2, CURLOPT_POST, true); // to send info
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch2, CURLOPT_COOKIEJAR, 'cookie.txt'); // to save cookie data for login
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true); // to get the html
$response2 = curl_exec($ch2);
curl_close($ch2);

$html = new simple_html_dom();
$html->load($response2);

$val = $html->find('input[name=form_key]');
$form_key = $val[0]->value;

$data = array(
    'form_key' => $form_key,
    'login[username]' => 'myusername',
    'login[password]' => 'mypassword',
    'send' => '',
);