Objective C: How to use addTarget:action:forControlEvents: method?
Asked Answered
S

2

12

I am trying to update the date and time displayed in a table cell immediately after the UIPicker's data has changed (real time updated). I implemented the following code. My "update" method is not being called despite changing the values in the picker. Can anyone advise? Thanks!

Zhen

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSUInteger row = [indexPath row];
    if (row == 0) 
    {
        self.picker.hidden = NO;

        [self.picker addTarget:self action:@selector(updateDate) forControlEvents:UIControlEventTouchUpInside];

    }

}

- (void)updateDate
{
    selectedDate = [self.picker date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];

    selectedDateString = [formatter stringFromDate:selectedDate];

    [tableView reloadData];
}
Selfexecuting answered 19/5, 2011 at 6:28 Comment(0)
E
19

You need to put a colon after the selector name.

[self.picker addTarget:self action:@selector(updateDate:) forControlEvents:UIControlEventTouchUpInside];

Also, the updateDate method should take an object of type id.

- (void) updateDate:(id) obj { }
Exhortation answered 19/5, 2011 at 6:52 Comment(5)
That's what I was going to suggest too.Yawata
thanks for the response. Can I check why adding the (id) obj is necessary? Anyway I tried to add the colon and id Obj but it still doesnt work, my method still doesn't get triggered.Selfexecuting
I found the issue. It seems that the picker is not responding to the event "UIControlEventTouchUpInside". I changed the event to "UIControlEventValueChanged" and it works now. Thanks!Selfexecuting
This answer is not correct. You do NOT need to put a color after the selector name, and you do NOT need to add a parameter to the method.Orson
@Orson You are right, the parameter is optional. However, if you do specify a colon in the selector and a parameter in the method, the parameter will be the object that the target was set on.Eadie
S
1

change in your code -

[self.picker addTarget:self action:@selector(updateDate:) forControlEvents:UIControlEventTouchUpInside];

to

[self.picker addTarget:self action:@selector(updateDate:) forControlEvents:UIControlEventAllEvents];

you can also handle it in UIPicker delegates.

Safety answered 19/5, 2011 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.