Search code examples
iphonecocoa-touchios4uiscrollviewuibutton

How to add buttons dynamically along with the scrollview in iPhone SDK?


In my iPhone app, I have to put buttons dynamically along with the scrollView.

Now I need to have button Click events associated with each of the buttons and perform a specific action on each button click.

My buttons have a title which is ASCII art. So creating common IBAction and performing the action based on the button title wont be a easy option in this case.

What can be the other options?

How can I associate the button click event with the specific button?


Solution

  • I think you can use the tag property of UIView.

    My program may be like following.

    - (NSInteger)encodeTagForButtonID:(NSString *)buttonID;
    - (NSString *)decodeButtonIDFromEncodedTag:(NSInteger)tag;
    

    When I create a UIButton, I encode the ID of the button to tag. buttonID may be something meaningful, or it is just an integer, like defined values. The signature of action can be this form: -(void)buttonAction:(id)sender;, and I can retrieve the tag value from sender.

    Edit:

    For example, in the UITableView's data source method.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *identifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
               /// new an autoreleased cell object
        }
    
        // Configure cell
        cell.tag = [self encodeTagWithIndexPath:indexPath];
    
        return cell;
    }
    

    When I touch this cell, I retrive indexPath from tag.

    UIButton is a subclass of UIView, so it has tag too. For example, I made a custom actionSheet, it contains a list of UIButtons. When I push down a UIButton, I need to know which button I pressed. So, I assign the row information to tag.

    NSArray *buttonListInActionSheet = ....; ///< UIButton array, a button per row.
    for (int idxBtn = 0; idxBtn < [buttonListInActionSheet count]; ++idxBtn) {
        UIButton *btn = [buttonListInActionSheet objectAtIndex:idxBtn];
        btn.tag = (100 + idxBtn);
    }
    

    When I touch the button, I can get the row information by

    - (void)buttonTouched:(id)sender {
       UIButton *btn = (UIButton *)sender;
       NSInteger idxBtn = (btn.tag - 100);
    }