2014-12-03 36 views
7

我在我的UITextFields上將UIKeyboardType設置爲UIKeyboardTypeNumberPad。但是,這隻允許用戶輸入正整數。我需要用戶能夠輸入負值或正值的整數。是否有一個與UIKeyboardTypeNumberPad相同的UIKeyboardType,但也包含「 - 」(減號)符號,如果沒有,我可以創建它嗎?是否有像數字鍵盤一樣的UITextField鍵盤類型,但允許使用負數?

謝謝。

+0

創建自定義鍵盤 – Sport 2014-12-03 12:48:36

+0

其他選項,添加一個減號( - )按鈕作爲一個inputAccessoryView。或者很滿意:UIKeyboardTypeNumbersAndPunctuation – 2014-12-03 12:55:16

+0

@OnikIV如何添加一個減號按鈕作爲inputAccessoryView? – AndyW 2014-12-03 13:07:07

回答

7

惱人的是,沒有這樣的系統鍵盤可用。除了創建自定義鍵盤之外,最好的選擇是UIKeyboardTypeNumbersAndPunctuation,並執行驗證以強制執行有效的數字輸入。

+1

UIKeyboardTypeDecimalPad雖然沒有顯示減號按鈕。爲了整潔,我希望它只是所需的鍵,所以必須考慮創建一個自定義的鍵。 – AndyW 2014-12-03 13:12:55

+0

哎呀抱歉,我的意思是UIKeyboardTypeNumbersAndPunctuation,但複製/粘貼錯誤。編輯答案。 – Clafou 2014-12-03 13:15:14

+0

在這種情況下,這實際上是我目前正在做的事情,但它對所有標點符號看起來有點垃圾,您甚至可以在此鍵盤上切換到字母表。 – AndyW 2014-12-03 14:03:59

2

添加一個減去accesoryView,你需要有你的textField作爲一個屬性,在這個例子中這個屬性是:myTextField;

你需要添加,創建你的myTextField這個代碼後,b.e.在viewDidLoad中:

 UIView *inputAccesoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)]; 
// It´s good idea a view under the button in order to change the color...more custom option 
inputAccesoryView.backgroundColor = [UIColor whiteColor]; 

UIButton *minusButton = [[UIButton alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-150)/2, 5, 150, 30)]; 
// configure the button here... you choose. 
[minusButton setTitle:@"-" forState:UIControlStateNormal]; 
[minusButton addTarget:self action:@selector(changeNumberSing) forControlEvents:UIControlEventTouchUpInside]; 
[inputAccesoryView addSubview:minusButton]; 

self.myTextField.inputAccessoryView = inputAccesoryView; 

,並添加您的viewController此按鈕的方法:

-(void)changeNumberSing 
{ 
if ([self.myTextField.text hasPrefix:@"-"]) 
{ 
    self.myTextField.text = [self.myTextField.text substringFromIndex:1]; 
}else 
{ 
    self.myTextField.text = [NSString stringWithFormat:@"-%@",self.myTextField.text]; 
} 
} 
+0

這個工程!只需將按鈕標題顏色設置爲黑色即可查看文本。這是在鍵盤上方,是否有可能在鍵盤左下方的區域(這是該鍵盤類型的空白區域)? – AndyW 2014-12-03 15:19:12

+0

不可以。您可以在鍵盤上方繪製。 (b.e更改按鈕的'y',並且按鈕將位於鍵盤上方)。但它不會收到任何事件。 – 2014-12-03 16:00:39

+0

這很煩人。儘管感謝您的幫助! – AndyW 2014-12-03 16:50:21