Search code examples
iosobjective-cuitableviewuitextfieldtouchesbegan

touchesBegan not called when textfield is in uitableview's cell


so i have a textfield, i have the UITextFieldDelegate in .h file. i declare the textfield in .m file:

UITextField * titletextfield

i put the textfield in one of the cell of a table view. i set the textfield delegate to self,

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row==0) {
    static NSString *CellIdentifier = @"Title";
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UILabel * label;
    if (cell == nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        label = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 90.0, cell.frame.size.height)];
        label.text =@"sth :";
        label.font=[UIFont systemFontOfSize:14.0];
        label.textColor =[UIColor grayColor];

        titletextfield =[[UITextField alloc]initWithFrame:CGRectMake(100, 0, cell.frame.size.width-100.0, cell.frame.size.height)];
        self.titletextfield.delegate=self;

        UIView *message = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.frame.size.width, cell.frame.size.height)];
        message.tag = 0;
        message.backgroundColor =[UIColor clearColor];
        [message addSubview:label];
        [message addSubview:titletextfield];
        [cell.contentView addSubview:message];
    }
    return  cell;}

touch begin was never called:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"123");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
NSLog(@"22");

}

when i unchecked the user interaction enabled from the tableview, the touchbegan function is start getting called. however,in this cad, i can not set focus on textfield anymore. anyone has the same problem before? thanks!


Solution

  • Here what is happening means When you enable UITableview "user interaction enable" property then all the touches are observed by the UITableview's scrollview.At this time all the sub views of UITableview's scrollview get the touch events(in this case your uitextfield also).so touchesBegan method of your viewcontroller's view never call.if you disable UITableview "user interaction enable" property then all touch events are not observed by the UITableview's scrollview and given to viewcontroller's view .At this time touchesBegan will be called.