2013-02-10 40 views
3

我的應用程序創建和存儲EKEvents到標準的日曆數據庫阻止用戶,但是,我發現,如果我用表情的「筆記」的事件,它嘗試從日曆中讀取事件時會導致崩潰。的UITextField - 打字非標準字符(如表情符號)

我不希望需要event.notes使用表情符號。我碰巧正在測試,當它讓我保存事件時,我感到非常震驚。

所以我覺得我的問題是可以解決的2路,均未我已經能夠找出一個(大頭貼甚至在自己的日曆顯示)。

1)我可以禁用或隱藏的自定義鍵盤按鍵? < --I'd喜歡這種解決方案

enter image description here

2)如果沒有,我如何創建一個字符集,包括所有的在所有的標準鍵盤的可能的字符來檢查的時候做對確定用戶沒有輸入表情符號?

我試過使用一些標準字符集來檢查,如alphanumericCharacterSet,但是使用它,我無法輸入空格。

下面是我使用至今,所要檢查的字符用戶鍵入代碼:

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    if (string.length == 0) { 
     return YES; 
    } 

    NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet]; 
    for (int i = 0; i < [string length]; i++) { 
     unichar c = [string characterAtIndex:i]; 
     if ([myCharSet characterIsMember:c]) { 
      return YES; 
     } 
    } 

    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Invalid Input" message:@"Oops! You can't use that character." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 
    [av show]; 
    return NO; 
} 

編輯:澄清錯誤

沒有錯誤,只有一次崩潰。 我的應用程序保存日曆事件,並將它們以列表形式顯示給用戶。 然後,用戶可以將事件標記爲「已付」或「未付款」,此時我將一個字符串附加到事件「 - 付費」的.notes屬性中。當我重新加載表格時,如果支付了事件,它會向用戶顯示一個特定的圖標。 當保存甚至有一個表情符號作爲.notes財產,我嘗試追加.notes的崩潰發生。

NSMutableCharacterSet *myCharSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy]; 
    [myCharSet formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]; 

這裏是可用的字符集列表可供選擇:

+0

如果事件說明中有表情符號字符,您會得到什麼錯誤?你最好的解決方案可能是解決這個問題。 – rmaddy 2013-02-10 17:19:00

+0

@rmaddy它不是一個錯誤,他只是不想要它,乾淨的文本會被有趣的圖標 – raceworm 2013-02-10 17:23:55

+0

@rmaddy,請參閱我的編輯。我解釋了到底發生了什麼。 – jhilgert00 2013-02-10 17:24:51

回答

6

您可以使用工會添加更多的允許的字符組合NSCharacterSet小號

controlCharacterSet 
whitespaceCharacterSet 
whitespaceAndNewlineCharacterSet 
decimalDigitCharacterSet 
letterCharacterSet 
lowercaseLetterCharacterSet 
uppercaseLetterCharacterSet 
nonBaseCharacterSet 
alphanumericCharacterSet 
decomposableCharacterSet 
illegalCharacterSet 
punctuationCharacterSet 
capitalizedLetterCharacterSet 
symbolCharacterSet 
newlineCharacterSet 

而且,你的代碼是檢查確保任何字符不在集合之外;我認爲你的意圖是檢查所有字符是不是在集外。 (這僅適用於用戶一次輸入多個字符的情況 - 請考慮複製和粘貼)。

考慮調整你的循環看起來更像這樣:

NSCharacterSet *myCharSet = [NSCharacterSet alphanumericCharacterSet]; 
for (int i = 0; i < [string length]; i++) { 
    unichar c = [string characterAtIndex:i]; 
    if ([myCharSet characterIsMember:c] == NO) { 
     // add your user alert here 
     return NO; 
    } 
} 

這樣,你的循環不會簡單地就可以找到的第一個人品好退出;相反,它會退出第一個壞字符。

+0

這是一個很好的建議蒂姆,謝謝:) – jhilgert00 2013-02-10 17:35:06

+2

只用'-rangeOfCharacterFromSet:'比自己迭代unichar更容易。 – Tricertops 2013-02-10 18:04:56

+0

好點。正在尋找這方面的東西。 – Tim 2013-02-10 18:17:09