通过LongPress更改UITextField BackGround Color

时间:2013-09-07 11:15:58

标签: ios uitextfield

所有方框都是UITextField个。当用户长按UITextField时,我想要更改背景颜色 哪个TextField长按了UITextField颜色,而不是所有UITextField

In My View

2 个答案:

答案 0 :(得分:3)

尝试使用这样......

- (void)viewDidLoad
{
    [super viewDidLoad];
    UILongPressGestureRecognizer *gs = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(changeBackground:)];
    [textFld addGestureRecognizer:gs];
}

- (void)changeBackground:(UIGestureRecognizer *)gs
{
     [self.view endEditing:YES]; // Edited 

     UITextField *txtFld = (UITextField *)gs.view;

     [txtFld setBackgroundColor:[UIColor redColor]];
}

答案 1 :(得分:1)

您可以使用UILongPressGestureRecognizer。请注意,一个手势识别器可以附加到一个视图 这是代码示例

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Array that holds your textfields
    NSArray *myTextFields;
    for (UITextField *textField in myTextFields) {
        //Creating UILongPressGestureRecognizer
        UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
        //Attaching it to textfield
        [textField addGestureRecognizer:longPressGestureRecognizer];
    }
}
//Handling long press
- (void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    UITextField *textField = (UITextField *)gestureRecognizer.view;
    textField.backgroundColor = [UIColor greenColor];
}