![](/img/trans.png)
[英]Trying to disable a button when not all UITextFields are populated in iOS
[英]Trying to see if both UITextFields inside of UITableViewRowCell contain text in iOS
我有一個UITableView包含自定義tableView單元格。 此自定義UITableViewCell包含兩個UITextField。 我為每個textFields分配了一個標簽值,我想確定兩個UITextFields是否都包含文本。 我想這樣做,因為用戶正在UITextFields中輸入值,這樣,一旦用戶在UITextField A中輸入了文本,並在UITextField B中輸入了字符,反之亦然(即用戶在UITextField B中輸入了文本,並且在UITextField B中輸入單個字符),則觸發事件或操作。 我意識到我需要使用UITextFieldDelegate方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {}
但是,我的問題是我不確定在使用此方法時如何同時引用兩個UITextFields。 我在使用此方法時似乎無法弄清楚如何獲取對活動的自定義UITableViewCell的引用。 有沒有人有什么建議?
您可以遍歷UITextField的超級視圖,直到找到UITableViewCell。 然后,您向tableview詢問該單元格的索引。
這就是我要做的:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
UITextField *theOtherTextField = nil;
// Get a list of sibling views of the textField
for( UIView *sub in textField.superview.subviews ){
if( textField!=sub && [sub isKindOfClass:[UITextField class]] ){
theOtherTextField = (UITextField *)sub;
}
}
// Now you have 'textField' and 'theOtherTextField' ready to use
}
順便說一句,這是您獲得對單元格的引用的方法,但這取決於您在UITableViewCell
的視圖層次結構中具有多深的文本字段:
UITableViewCell *cell = (UITableViewCell *)textField.superview.superview;
您可能將UITableView
設置為UITextFieldDelegate
。 如果您想要更改以使UITableViewCell
作為UITextFieldDelegate
,則可以避免上面的大多數麻煩。
在自定義單元格中,您有兩個屬性textField1和textField2引用了單元格中的兩個文本字段。 當調用委托textField:shouldChangeCharactersInRange:時,您將檢查使用上述兩個屬性:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (self.textField1.text.length > 0 && self.textField2.length > 0) {
// do what you want
}
}
您還可以檢測到該屬性與哪個文本字段對應:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.textField1) {
// text field 1's text changed
}
else if (textField == self.textField2) {
// and this is text field 2
}
}
不要使用shouldChangeCharactersInRange
! 我經常看到這種情況,而這並不是該方法的目的。 該方法用於停止無效輸入,例如在數字字段中輸入字母。
而是子類化UITableViewCell
並創建自定義單元格。 給它幾個IBAction,並使其UITextFields
通過EditingChanged
事件連接到那些動作。 從那里跟蹤其中的值。 如果您想窺視這些值,也可以給該班幾個IBOutlets。
在您的自定義單元中,由於已經標記了它們,因此可以在這些標記的幫助下訪問TextField。 創建兩個textFields的私有實例,然后在initWithStyle內,為它們分配textFields標簽。
_textField1 = [self viewWithTag:tag1];
_textField2 = [self viewWithTag:tag2];
_textField1.delegate = self;
_textField2.delegate = self;
現在在textField Delegate方法內,您可以檢查兩個textField的文本長度。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(_textField1.text.length > 0 && _textField2.text.length > 0){
// write the action you want to do here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.