2014-02-21 5 views
1

я создал 2 UITextField с и UIButton программным способом, когда я нажимаю UIButton Я хочу, чтобы изменить текст выделенного UITextField но не изменяя текст второго UITextField выделенным один.Невозможно изменить текст UITextField

-(void)viewDidLoad 
{ 
    txtf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 586, 45)]; 
    txtf.borderStyle = UITextBorderStyleNone; 
    txtf.backgroundColor = [UIColor clearColor]; 
    txtf.font = [UIFont systemFontOfSize:17]; 
    txtf.autocorrectionType = UITextAutocorrectionTypeNo; 
    txtf.keyboardType = UIKeyboardTypeDefault; 
    txtf.returnKeyType = UIReturnKeyDone; 
    txtf.textAlignment = NSTextAlignmentLeft; 
    txtf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
    [self.view addSubview:txtf]; 

    txtf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 586, 345)]; 
    txtf.borderStyle = UITextBorderStyleNone; 
    txtf.backgroundColor = [UIColor clearColor]; 
    txtf.font = [UIFont systemFontOfSize:17]; 
    txtf.autocorrectionType = UITextAutocorrectionTypeNo; 
    txtf.keyboardType = UIKeyboardTypeDefault; 
    txtf.returnKeyType = UIReturnKeyDone; 
    txtf.textAlignment = NSTextAlignmentLeft; 
    txtf.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
    [self.view addSubview:txtf]; 
} 

- (IBAction)change:(id)sender 
{ 
    txtf.text = @"the text was changed" 
} 

есть ли способ решить эту проблему?

+1

Что делать вы подразумеваете под «выделенным текстовым полем»? У кого есть фокус? – Antonio

+0

@ Антонио да, я имею в виду сосредоточенное текстовое поле – AFB

ответ

3

Изменить код

-(void)viewDidLoad{ 
txtf1 = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 586, 45)]; 
txtf1.borderStyle = UITextBorderStyleNone; 
txtf1.backgroundColor = [UIColor clearColor]; 
txtf1.font = [UIFont systemFontOfSize:17]; 
txtf1.autocorrectionType = UITextAutocorrectionTypeNo; 
txtf1.keyboardType = UIKeyboardTypeDefault; 
txtf1.returnKeyType = UIReturnKeyDone; 
txtf1.textAlignment = NSTextAlignmentLeft; 
txtf1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
[self.view addSubview:txtf1]; 

txtf2 = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 586, 345)]; 
txtf2.borderStyle = UITextBorderStyleNone; 
txtf2.backgroundColor = [UIColor clearColor]; 
txtf2.font = [UIFont systemFontOfSize:17]; 
txtf2.autocorrectionType = UITextAutocorrectionTypeNo; 
txtf2.keyboardType = UIKeyboardTypeDefault; 
txtf2.returnKeyType = UIReturnKeyDone; 
txtf2.textAlignment = NSTextAlignmentLeft; 
txtf2.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; 
[self.view addSubview:txtf2]; 
} 

- (IBAction)change:(id)sender { 
txtf2.text = @"the text was changed" 
} 

И добавить txtf2 членам класса.

UPDATE:
Для изменения выделены UITextField изменения - (IBAction)change:(id)sender в

- (IBAction)change:(id)sender 
{ 
    if (txtf1.isHighlighted) { 
     txtf1.text = @"the text 1 was changed"; 
    } 
    else if (txtf2.isHighlighted) { 
     txtf2.text = @"the text 2 was changed"; 
    } 
    else { 
     NSLog(@"none of the textField is Highlighted"); 
    } 
} 

UPDATE 2 Если у вас есть много текстовых полей, которые вы можете попробовать следующее

for (id subview in self.view.subviews) { 
    if ([subview isKindOfClass:[UITextField class]]) { 
     UITextField *textField = subview; 
     if (textField.isHighlighted) { 
      textField.text = @"the text was changed"; 
     } 
    } 
} 
+1

Что вы изменили ???? – Popeye

+0

Я изменил 'txtf' на' txtf1' и 'txtf2' – Avt

+0

Я использовал этот метод, но я хочу изменить текст выделенного текстового поля, как узнать, выделено ли это выделение или нет. – AFB

2

txtf всегда указывает на второй текст. так что проблема.

Когда вы создали первый UItextFied, txtf указывает на него. Но когда вы создаете новый UITextField и делаете для него txtf, , то ссылка с первым текстовым полем теряется.

И в вашем методе change вы всегда получаете reference of second textfield и меняете его.

два варианта,
1) используют txtf1 и txtf2, два свойства класса
2) использование тегов. [UIView viewWithTag:tagValue];

Использование Tag's->
Предполагая numberOfTextFields вы используете 3.

txtf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 586, 45)]; 
//set its properties 
txtf.tag=1; 
[self.view addSubview:txtf]; 

txtf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 586, 45)]; 
//set its properties 
txtf.tag=2; 
[self.view addSubview:txtf]; 

txtf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 586, 45)]; 
//set its properties 
txtf.tag=3; 
[self.view addSubview:txtf]; 

метод изменения Modify в

- (IBAction)change:(id)sender 
{ 
    NSInteger numberOfTextFields=3; 
    UITextField *textField; 
    for (int i=1; i<=numberOfTextFields; i++) { 
     textField=(UITextField*)[self.view viewWithTag:i]; 
     if(textField.isHighlighted==YES) 
      break; 
     else 
      textField=nil; 
    } 

    if(textField==nil){ 
     NSLog(@"none is highlightes"); 
    } 
    else{ 
     textField.text= @"new text for highlighted textField"; 
    } 
} 
1

Поскольку ваш и UITextField имеет то же имя (txtf), Итак, сначала измените имя первого или второго UITextField. Другой разумный код правильный. :)

Отредактировано:

Просто сделать более правильный @ обновленный ответ АВТ в.

- (IBAction)change:(id)sender 
{ 
    if (txtf1.isHighlighted) { 
     txtf1.text = @"the text 1 was changed"; 
    } 
    else if (txtf2.isHighlighted) { 
     txtf2.text = @"the text 2 was changed"; 
    } 
    else { 
     NSLog(@"none of the textField is Highlighted"); 
    } 
} 
Смежные вопросы