使用sender标签在UI按钮点击事件时更新UITableViewCell的标签

Pra*_*inh 1 iphone uibutton uitableview ios

在我的应用程序中,我在UITableviewCell中动态创建动态UILabel和UIButton.他们的标签是UITableviewCell indexPath.row.我想在UIButton的click事件上更新UILabel,它具有相同的UIButton标记.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"UIGridViewRow";
    MyCustomCell *Cell  = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (Cell == nil)
    {
         btnHeart = [UIButton buttonWithType:UIButtonTypeCustom];
         [btnHeart setFrame:CGRectMake(150,350,20,20)];
         [btnHeart setImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
         [btnHeart addTarget:self action:@selector(HeartPressed:) forControlEvents:UIControlEventTouchDown];
         btnHeart.tag = indexPath.row;
         [cell addSubview:btnHeart];

         lblHeart = [[UILabel alloc] initWithFrame:CGRectMake(175, 350, 20, 20)];
         [lblHeart setBackgroundColor:[UIColor clearColor]];
         [lblHeart setTextColor:[UIColor whiteColor]];
         [lblHeart setTag:indexPath.row];
         [lblHeart setText:[NSString stringWithFormat:@"%@",[[appdel.PhotoAry objectAtIndex:photo.tag] valueForKey:@"Hearts"]]];
         [cell addSubview:lblHeart];
    }
}

-(IBAction)HeartPressed:(id)sender
{
     urlString = [NSString stringWithFormat:@"http://zealousys.com/PeekaBoo_Webservice/heart.php?uid=%@&pid=%@",appdel.strUserid,[[appdel.PhotoAry objectAtIndex:[sender tag]] valueForKey:@"ImageID"]];

     NSURL *url = [[NSURL alloc]initWithString:urlString];
     NSURLRequest *request = [NSURLRequest requestWithURL:url];
     NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
     NSError *myError = nil;
     NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves error:&myError];
     lblHeart.text = [NSString stringWithFormat:@"%@",[res valueForKey:@"Hearts"]];
}
Run Code Online (Sandbox Code Playgroud)

在这里,我想更新lblHeart,它与UITableviewCell的HeartPressed事件中的btnHeart标签具有相同的标签.

Gya*_*ngh 5

您需要在点击索引处获取UITableViewCell,之后您可以在UITableViewCell内更新标签

NSIndexPath *likedIndex = [NSIndexPath indexPathForRow:sender.tag inSection:0];

MyCustomCell *cell = (MyCustomCell *)[self.table cellForRowAtIndexPath:likedIndex];

          for (UIView *subView in cell.subviews) {

              if ([subView isKindOfClass:[UILabel class]]) {

                    //sender.tag = button tag
                  if (subView.tag == sender.tag) {

                      [(UILabel *) subView setText:@"Hearts"];
                  }
              }
          }
Run Code Online (Sandbox Code Playgroud)

希望它可能有所帮助.