2017-05-04 52 views
0

我使用斯威夫特3火力創建一個社交應用,用戶可以使職位,但事情是,我不希望用戶使用罵人的話如何阻止用戶在Swift 3中寫入詛咒單詞?

有沒有辦法像取代這些詞當用戶寫他們?
目前用戶使用文本視圖寫他們想發佈的東西...

我怎樣才能做到這一點像最簡單,最簡單的方法是什麼?

我在找答案,我發現這個問題Swift: how to censor/filter text entered for swear words, etc?
這個答案代碼:

import Foundation 

func containsSwearWord(text: String, swearWords: [String]) -> Bool { 
return swearWords 
    .reduce(false) { $0 || text.contains($1.lowercased()) } 
} 

// example usage 
let listOfSwearWords = ["darn", "crap", "newb"] 
    /* list as lower case */ 

let userEnteredText1 = "This darn didelo thread is a no no." 
let userEnteredText2 = "This fine didelo thread is a go." 

print(containsSwearWord(text: userEnteredText1, swearWords: listOfSwearWords)) // true 
print(containsSwearWord(text: userEnteredText2, swearWords: listOfSwearWords)) // false 

但我真的不明白這一點。我如何在我的項目中實現?我應該在哪裏粘貼該代碼?或者我如何將該代碼鏈接到我的文本視圖?它在代碼中缺少的東西應該是什麼?

回答

0

如果在.editingChanged事件上使用UITextField。

inputTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) 

func textFieldDidChange(_ textField: UITextField) { 
     print(containsSwearWord(text: textField, swearWords: listOfSwearWords)) // Here you check every text change on input UITextField 
} 

UPDATE

輸入端

之前在textViewShouldEndEditing(_ textView: UITextView)驗證用戶輸入您必須實現UITextViewDelegateOfficial Documentation

驗證並返回true/false來允許編輯結束。

輸入端

textViewDidEndEditing(_ textView: UITextView)驗證用戶輸入並顯示任何警告,如果您發現不準的話驗證了。

+0

但是,如果我使用一個UITextView會發生什麼?我仍然不明白! 謝謝。 – killerwar557

+0

我已經更新了我對UITextView用法的回答。 – sergiog90

0

這就是我該怎麼做的。

  • 通行證的TextView文字的NSString
  • 轉換的NSString的NSArray
  • 檢查,看看是否能NSArray中包含你的詛咒字符串之一。如果確實如此,那就用****或其他東西代替它。

這就是它在Objective-C中的樣子。

NSString *textViewStr = myTextView.text; 
NSArray *myArray1 = [textViewStr componentsSeparatedByString:@" "]; //this will put all words separated by space into an array 
if ([myArray1 containsObject:@"crap"]) { 
    //found one 
    textViewStr = [textViewStr stringByReplacingOccurrencesOfString:@"crap" 
            withString:@"duck"]; 
} 

雖然使用谷歌搜索,我發現了另一個更好的答案。

//If you want multiple string replacement: 
NSString *s = @"foo/bar:baz.foo"; 
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."]; 
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""]; 
NSLog(@"%@", s); // => foobarbazfoo 

String replacement in Objective-C