处理UITableviewcell中的按钮事件

时间:2012-02-17 12:04:53

标签: iphone ios events uitableview uibutton

我试图从数组中获取一个数字并将其存储在UITableview单元格中的按钮中。当我点击按钮时,我应该可以获得该号码。什么是在按钮点击事件中从发件人那里获取信息的正确方法

这就是我的尝试。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil )
{
    UIButton *button = [[[UIButton alloc]init]autorelease];
    CGRect frame = CGRectMake(180, 10, 33, 33);
    button.frame = frame;
    button.tag = 1001;

    UIImage *image = [[[UIImage alloc]init]autorelease];
    image = [UIImage imageNamed:@"icon.png"];
    [button setBackgroundImage:image forState:UIControlStateNormal];

    [button addTarget:self action:@selector(onIconTapped)  forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor clearColor];
    [button setHidden:YES];
    cell.accessoryView = button;  

}

int myContactID = contact.contactID;
NSLog(@"My No.  %d", myContactID);
NSNumber *mySelectedNumber = [NSNumber numberWithInt:myContactID];

UIButton *myButton = (UIButton *)[cell.accessoryView viewWithTag:1001];
for(int i = 0; i< [myContactsArray count]; i++){
    if([[[myContactsArray objectAtIndex:i]valueForKey:@"RecordID"] isEqualToNumber:mySelectedNumber]){

        [myButton setHidden:NO];
        NSString *myString;
        myString = [[myContactsArray objectAtIndex:i]valueForKey:@"MYNumber"];
        [myButton setTitle:myString forState:UIControlStateNormal];
        myButton.titleLabel.font = [UIFont systemFontOfSize:0];
        NSLog(@"my number %@", myString);
        NSLog(@"Button tag %@", myButton.currentTitle);
        break;
    }
    else{
       [myButton setHidden:YES];
    }
}
}



-(void)onIconTapped:(id)sender{
}

3 个答案:

答案 0 :(得分:2)

这种方法来自iOS Recipes(Matt Drance):您可以通过将按钮的原点转换为tableView(convertPoint:toView:)来获取单元格,然后调用

[[self tableView] indexPathForRowAtPoint: convertedPoint];

答案 1 :(得分:2)

-(void)onIconTapped:(id)sender{

  if (sender.tag == 1001){
  NSString *title = sender.currentTitle;

  NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
  [formatter setNumberStyle:NSNumberFormatterDecimalStyle];

  NSNumber *titleNumber = [numberFormatter numberFromString:title]; 
  }
}

答案 2 :(得分:0)

1

[button addTarget:self action:@selector(onIconTapped:) `enter code here`forControlEvents:UIControlEventTouchUpInside];

2

myString = [[myContactsArray objectAtIndex:i]valueForKey:@"MYNumber"];
button.tag = i;`

3

-(void)onIconTapped:(id)sender{
Contact *contact = [myContactsArray objectAtIndex:sender.tag];

}