2017-08-25 79 views
-1

我已經搜索了很多,但未能找到解決我的問題的方法。在iOS中的文本字段中替換空格的特殊字符

我有一個文本字段,用戶在其中輸入數據。輸入的文本可能包含空格,我想用%20的順序替換這些出現的內容。

這並不重要,有多少空間;每當有空間時,應該用%20代替。

+0

很容易'urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];' –

+0

可以解釋你的答案嗎? @MikeAlter – Oneeb

+0

這不是答案。但stringByAddingPercentEncodingWithAllowedCharacters會自動添加%20,其中字符串中的空格試試IT –

回答

1

%20

@implementation ViewController 
{ 
NSString *result 
} 

result=self.txtField.text; 
result=[result stringByReplacingOccurrencesOfString:@" " withString:@"%20"]; 

更換空間,如果當用戶在文本字段中輸入文本您想要編輯然後TextFiled的TextChanged事件使用。

此線在viewDidLoad中

[self.txtField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; 

-(void)textFieldDidChange :(UITextField *)theTextField{ 
result=self.txtField.text; 
result=[result stringByReplacingOccurrencesOfString:@" " withString:@"%20"]; 
//just use this result where you want 
} 
+0

我們的代碼工作正常,但是當我們給出空間時,這個字符%20顯示在屏幕上,我希望它不顯示在屏幕上,當用戶給出空間時,它應該在文本字段中顯示空格,但是在後端當值爲pass時,它應該在有空格的地方通過%20。 @Zaheer Udeen Babar – Oneeb

+0

@Oneeb只是將結果設置爲您想要使用它的變量?只是不分配結果迴文本字段,刪除self.txtField.text =結果; – 3stud1ant3

+0

刪除此行self.txtField.text = result;正如@ user1000所建議的。 –

0

請使用此代碼:

目標C:

NSString *string = textField.text; 

      string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]]; 

斯威夫特:

var string: String = textField.text 
string = string.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) 

返回不替換與%的編碼字符集allowedCharacters所有字符從接收器做了一個新的字符串。

+0

謝謝,我得到了我的答案。 @Surabh Jain – Oneeb

+0

你有沒有試過這個? @Oneeb –

+0

不,我沒有在這之前得到答案。:) @Saurabh Jain – Oneeb

相關問題