如何在按钮单击时突出显示目标c中的空白文本字段

时间:2017-01-03 05:35:18

标签: ios objective-c

如果在目标c中点击按钮时textfield为空,我想突出显示特定的文本字段。突出显示一些红色(字段为空)的文本,如错误按摩,但在相应的文本字段前面,不在警报视图中

5 个答案:

答案 0 :(得分:1)

首先在项目中导入<QuartzCore/QuartzCore.h>

然后,您可以通过调用subviews方法获取数组中的所有子视图:

-(void)checkTextFieldIsEmpty{

   NSArray *myarr = [self.view subviews];
   NSString *emptyTextFieldName = [[NSString alloc]init];

   for (int i = 0; i < myarr.count; i++) {
      if ([[myarr objectAtIndex:i] isKindOfClass:[UITextField class]]) {
         UITextField *tempTextField = (UITextField*)[myarr objectAtIndex:i];
            if (tempTextField.text.length >0) {
               NSLog(@"textfield have some text");
            }
            else{
               NSLog(@"textfield is empty");
                   //Change color here like following way
                   //tempTextField.layer.borderColor = [[UIColor redColor]CGColor];
                }
           }    
       }
    }

答案 1 :(得分:0)

试试此代码

 self.stremail=[self.txtemail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
self.strpass=[self.txtpass.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];


if ((self.stremail.length==0) || (self.strpass.length == 0))
{
    if(self.stremail.length==0)
    {
    UIColor *color = [UIColor redColor];
    _txtemail.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_txtemail.placeholder attributes:@{NSForegroundColorAttributeName: color}];
    }else
    {
        UIColor *color = [UIColor redColor];
        _txtpass.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_txtpass.placeholder attributes:@{NSForegroundColorAttributeName: color}];

    }

}

答案 2 :(得分:0)

最好的方法是在文本字段中添加右视图

-(IBAction)yourButtonAction:(id)sender{

     if(yourTextField.text.lenght == 0){
           UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
          imageView.image = [UIImage imageNamed:@"yourImageName.png/jpg"];

          self.yourTextField.rightViewMode = UITextFieldViewModeAlways;
          self.yourTextField.rightView = imageView;
         }

   }

//和TextField的Delegate方法

- (void)textFieldDidBeginEditing:(UITextField *)textField;


     if(yourTextField.isEditing == YES){
          self.yourTextField.rightViewMode = UITextFieldViewModeNever;
          }
    }

答案 3 :(得分:0)

您可以使用US2FormValidator库。只需将其添加到项目中,并将US2ValidatorTextField作为类名,并附带验证消息和一些属性。

答案 4 :(得分:0)

我认为您应该获得包含textFields的所有视图子视图 检查subview是否属于UItextField类,如果为空,则更改颜色:

for loop in self.view.subviews
{
   if([loop isKindOf:[UItextField class]] && loop.characters.count==0) {
      //change the Color of textField
   }
}