2012-01-14 2 views
0

Мне удалось переназначить переменные UITableViewCell и получить его для чириканья с TWTweetComposeViewController, но у меня возникла проблема. Он всегда чирикает переменные из последней строки в UITableView.Назначение переменных из UITableViewCell для твитов в главном контроллере представления

Вот моя установка: у меня есть 1 кнопка твитта и 4 UILabels в UITableViewCell. 4 UILabels извлекают информацию из Plist для заполнения таблицы. В каждой ячейке есть кнопка твита, чтобы чирикать информацию о ячейке, но тут я столкнулся с проблемой. Он всегда считывает информацию из последней строки таблицы, а не строку, в которой он находится. Любая помощь с благодарностью.

установка UITableViewCell.h

@property (nonatomic, strong) IBOutlet UILabel *playerOneLabel; 
@property (nonatomic, strong) IBOutlet UILabel *playerOneScoreLabel; 

@property (nonatomic, strong) IBOutlet UILabel *playerTwoLabel; 
@property (nonatomic, strong) IBOutlet UILabel *playerTwoScoreLabel; 

Главная View Controller:

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"ScoreListCell"; 

    ScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 

    NSDictionary * dictionary = [scoresArray objectAtIndex:indexPath.row]; 
    cell.playerOneLabel.text = [dictionary objectForKey:@"playerOneName"]; 
    cell.playerOneScoreLabel.text = [dictionary objectForKey:@"playerOneScore"]; 
    cell.playerTwoLabel.text = [dictionary objectForKey:@"playerTwoName"]; 
    cell.playerTwoScoreLabel.text = [dictionary objectForKey:@"playerTwoScore"]; 

    self.player1Name = cell.playerOneLabel; 
    self.player1Score = cell.playerOneScoreLabel;   
    self.player2Name = cell.playerTwoLabel; 
    self.player2Score = cell.playerTwoScoreLabel; 

    return cell; 
} 

и, наконец, установка твит в главном контроллере представления:

- (IBAction)twitter:(id)sender { 

    if ([TWTweetComposeViewController canSendTweet]) 
    { 
     TWTweetComposeViewController *tweetSheet = 
     [[TWTweetComposeViewController alloc] init]; 
     NSString *text = [NSString stringWithFormat:@"%@-%@, %@-%@", 
          player1Name.text, player1Score.text, player2Name.text, player2Score.text]; 
     [tweetSheet setInitialText:text]; 
     [self presentModalViewController:tweetSheet animated:YES]; 
    } 
    else 
    { 
     UIAlertView *alertView = [[UIAlertView alloc] 
            initWithTitle:@"Sorry"                
            message:@"Tweet unsuccessful. Make sure your device has an internet connection and you have a Twitter account."               
            delegate:self            
            cancelButtonTitle:@"OK"             
            otherButtonTitles:nil]; 
     [alertView show]; 
    } 
} 
+0

вы должны добавить теги к каждой метке, а затем получить доступ к ним с помощью тега через параметр отправителя – cpjolicoeur

ответ

1

Вы неправильно при условии, что ячейка создается/создается в то же самое время, когда пользователь нажимает эту кнопку твитта.

Вы можете, например, добавить тег в твит-кнопки, которая отражает индекс строки это показано в.

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"ScoreListCell"; 

    ScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 

    //assign the row-index as a button tag - 
    //NOTE: this misses the way you fetch/create your tweetButton - 
    //  that would have to left to you as you missed to quote 
    //  that part in your sources 
    UIButton *tweetButton = ???; 

    tweetButton.tag = indexPath.row; 

    NSDictionary * dictionary = [scoresArray objectAtIndex:indexPath.row]; 
    cell.playerOneLabel.text = [dictionary objectForKey:@"playerOneName"]; 
    cell.playerOneScoreLabel.text = [dictionary objectForKey:@"playerOneScore"]; 
    cell.playerTwoLabel.text = [dictionary objectForKey:@"playerTwoName"]; 
    cell.playerTwoScoreLabel.text = [dictionary objectForKey:@"playerTwoScore"]; 

    return cell; 
} 

После того, что кнопка активирована, в рамках метода подключенного действия, вы просто принести что индексируйте назад из тега и используйте его для адресации правильных данных в вашем словаре.

Обратите внимание, что я оставил все проверки диапазона и дальнейшие защитные действия программирования для вас.

- (IBAction)twitter:(id)sender 
{ 
    UIButton *tweetButton = (UIButton *)sender; 
    unsigned int rowIndex = tweetButton.tag; 

    NSDictionary * dictionary = [scoresArray objectAtIndex:rowIndex]; 
    NSString *playerOneNameText = [dictionary objectForKey:@"playerOneName"]; 
    NSString *playerOneScoreText = [dictionary objectForKey:@"playerOneScore"]; 
    NSString *playerTwoNameText = [dictionary objectForKey:@"playerTwoName"]; 
    NSString *playerTwoScoreText = [dictionary objectForKey:@"playerTwoScore"]; 

    if ([TWTweetComposeViewController canSendTweet]) 
    { 
     TWTweetComposeViewController *tweetSheet = 
     [[TWTweetComposeViewController alloc] init]; 
     NSString *text = [NSString stringWithFormat:@"%@-%@, %@-%@", 
          playerOneNameText, playerOneScoreText, playerTwoNameText, playerTwoScoreText]; 
     [tweetSheet setInitialText:text]; 
     [self presentModalViewController:tweetSheet animated:YES]; 
    } 
    else 
    { 
     UIAlertView *alertView = [[UIAlertView alloc] 
            initWithTitle:@"Sorry"                
            message:@"Tweet unsuccessful. Make sure your device has an internet connection and you have a Twitter account."               
            delegate:self            
            cancelButtonTitle:@"OK"             
            otherButtonTitles:nil]; 
     [alertView show]; 
    } 
} 
+0

я на самом деле есть кнопка чирикать, установленную в главном контроллере, связывая его с действием «Touch Up Inside», что передавшим чирикать. Я попробую ваш код и посмотрю, работает ли он. Благодарю. –

+0

В вашем вопросе вы сказали нам, что каждая ячейка содержит твит-кнопку. Либо я ошибся, либо ваш комментарий не имеет смысла. – Till

+0

Возможно, я должен был быть более явным. Я использую раскадровку с динамическими ячейками прототипов. 4 метки и кнопка твита находятся внутри ячейки прототипа. Я объявляю метки в отдельном классе и кнопку в главном контроллере. Я могу чирикать, используя эту настройку, поэтому мне придется немного поэкспериментировать с вашим кодом. –

Смежные вопросы