Попытка получить содержимое ячейки UITableView при выборе пользователем - PullRequest
1 голос
/ 08 апреля 2010

Я установил приложение на основе UITableView, в котором есть .plist для хранения данных..Plist имеет словарь в качестве корня, за которым следует несколько массивов, каждый из которых содержит строки данных, которые отображаются в таблице.

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

Код компилируется нормально, без предупреждений или ошибок, и если я могу просто получить строкуВыбранная ячейка у меня будет хорошо на моем пути, поэтому любая помощь приветствуется.Я знаю, что мне нужно сделать больше, следуя части NSUInteger row = [indexPath row];, но здесь мой ум иссякает ...

Вот соответствующий раздел «выбор», если мне нужно опубликовать больше кода, пожалуйста, дайте мне знать, и я действительно ценю любую помощь с этим ... (пожалуйста, прости мое 'предупреждение' сообщение, я был просто счастлив в тот момент, когда я получаю ЧТО-ТО от выбора строки!)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
 [tableView deselectRowAtIndexPath:indexPath animated:YES];  
 NSUInteger row = [indexPath row];


 NSString *message = [[NSString alloc] initWithFormat:
  @"You selected Cell %d from this Section, "@"which is a very good choice indeed!"
  @"Unfortunately I can't work out how to get the info out of the cell so it's not much use at the moment!"
  @"Still, this is a good chance to see how much space I have in an alert box!", row];


UIAlertView *alert = [[UIAlertView alloc]

initWithTitle:@"My God! It works..."

message:message

delegate:nil

cancelButtonTitle:@"You are awesome Karl!!"

otherButtonTitles:nil];

[alert show];

[message release];
[alert release];

}

Обновление:

На самом деле, чтобы упростить задачу, вот ВСЕ код!Как я уже сказал, все, что я пытаюсь сделать, это вывести строковые данные из выбранной ячейки, оттуда я хочу открыть новое представление на основе результатов, поэтому все, что мне нужно на этом этапе, - это «результат»,

Я знаю, что код не очень красивый, и там должно быть много ошибок и т. Д., Но на данном этапе это не кажется важным, так как он компилируется и работает без проблем, я просто не получаю результатнужно от нажатия кнопки!

Любая помощь или совет будут высоко оценены, и если кто-то действительно может написать строку или около того кода, я должен вставить и объяснить, «почему», я был бы чрезмернолуна!

#import "my_firstApp.h"
#import "NSDictionary-MutableDeepCopy.h"

@implementation my_firstAppViewController

@synthesize names;
@synthesize keys;
@synthesize table;
@synthesize search;
@synthesize allNames;
@synthesize tempImageType;
@synthesize tempImageName;
@synthesize finalImageName;
@synthesize tempSubtitle;
@synthesize finalSubtitleName;
@synthesize tempSubtitleType;
@synthesize finalSubtitleText;
@synthesize setValue;


#pragma mark - 
#pragma mark Custom Methods
-(void)resetSearch {
    NSMutableDictionary *allNamesCopy = [self.allNames mutableDeepCopy];
    self.names = allNamesCopy;
    [allNamesCopy release];
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    [keyArray addObject:UITableViewIndexSearch];
    [keyArray addObjectsFromArray:[[self.allNames allKeys]
                                   sortedArrayUsingSelector:@selector(compare:)]];
    self.keys = keyArray;
    [keyArray release];
}
-(void)handleSearchForTerm:(NSString *)searchTerm {
    NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
    [self resetSearch];
    for (NSString *key in self.keys) {
        NSMutableArray *array = [names valueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];
    for (NSString *name in array) {
        if ([name rangeOfString:searchTerm
                        options:NSCaseInsensitiveSearch].location==NSNotFound)
            [toRemove addObject:name];
    }

    if ([array count] == [toRemove count])
        [sectionsToRemove addObject:key];

    [array removeObjectsInArray:toRemove];
    [toRemove release];
}
[self.keys removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[table reloadData];
}
- (void)viewDidLoad {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"dataList"
                                                     ofType:@"plist"];

                            NSDictionary *dict = [[NSDictionary alloc] 
                          initWithContentsOfFile:path];
    self.allNames = dict;
    [dict release];

    [self resetSearch];
    [table reloadData];
    [table setContentOffset:CGPointMake(0.0, 44.0) animated:NO];
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.names = nil;
    self.keys = nil;
    self.table = nil;
    self.search = nil;
    self.allNames = nil;
}
- (void)dealloc {
    [names release];
    [keys release];
    [table release];
    [search release];
    [allNames release];
    [tempImageName release];
    [tempImageType release];
    [finalImageName release];
    [tempSubtitle release];
    [finalSubtitleName release];
    [tempSubtitleType release];
    [finalSubtitleText release];
    [setValue release];

    [super dealloc];
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return ([keys count] >0) ?[keys count] : 1;

}
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    if ([keys count] ==0)
        return 0;
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    return [nameSection count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];




    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];

    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SectionsTableIdentifier ];


    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                       reuseIdentifier: SectionsTableIdentifier ] autorelease];


    }

    cell.textLabel.text = [nameSection objectAtIndex:row];
    tempSubtitle=[nameSection objectAtIndex:row];
    finalSubtitleText = [[NSBundle mainBundle] pathForResource:tempSubtitle ofType:@"txt"];
    NSString *fileContents = [NSString stringWithContentsOfFile:finalSubtitleText encoding:NSUTF8StringEncoding error:nil];
        cell.detailTextLabel.text = fileContents;
    cell.detailTextLabel.textColor = [UIColor grayColor];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];

    tempImageName=[nameSection objectAtIndex:row];
    tempImageType=@".png";
    finalImageName=[tempImageName stringByAppendingString:tempImageType];



    UIImage *image = [UIImage imageNamed:finalImageName];
    cell.imageView.image = image;

    return cell;





}
- (NSString *)tableView:(UITableView *)tableView 
titleForHeaderInSection:(NSInteger)section
{
    if ([keys count] == 0)
        return nil;

    NSString *key = [keys objectAtIndex:section];
    if (key == UITableViewIndexSearch)
        return nil;
    return key;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
if (isSearching)
return nil;

    return keys;
}

#pragma mark - 
#pragma mark Table View Delegate Methods
-(NSIndexPath *)tableView:(UITableView *)tableView
 willselectRowAtIndexPath:(NSIndexPath *)indexPath {
    [search resignFirstResponder];
    isSearching = NO;
    search.text = @"";
    [tableView reloadData];
    return indexPath;
}
#pragma mark - 
#pragma mark Search Bar Delegate Methods
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *searchTerm = [searchBar text];
    [self handleSearchForTerm:searchTerm];


}

-(void)searchBar:(UISearchBar *)searchBar
   textDidChange:(NSString *)searchTerm {
    if ([searchTerm length] ==0) {
        [self resetSearch];
        [table reloadData];
        return;
    }
    [self handleSearchForTerm:searchTerm];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    isSearching = NO;
    search.text = @"";
    [self resetSearch];
    [table reloadData];
    [searchBar resignFirstResponder];
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
    [table reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title
               atIndex:(NSInteger)index {
    NSString *key = [keys objectAtIndex:index];
    if (key == UITableViewIndexSearch) {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;

    }
    else return index;


}





    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];      







        NSUInteger row = [indexPath row];



    NSString *message = [[NSString alloc] initWithFormat:
        @"You selected Cell %d from this Section, "@"which is a very good choice indeed!"
        @"                                     Unfortunately I can't work out how to get the info out of the cell so it's not much use at the moment!"
        @"                            Still, this is a good chance to see how much space I will have for the info I need to present!", row];
                      UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"My God! It works..."
                      message:message
                      delegate:nil
                      cancelButtonTitle:@"You are awesome Karl!!"
                      otherButtonTitles:nil];
                      [alert show];

                      [message release];
                      [alert release];



}
@end

1 Ответ

2 голосов
/ 08 апреля 2010

Метод передает вам только порядковый номер того источника данных, который вы ему дали, поэтому верните его обратно к источнику данных, который вы использовали для ячеек UITableView (я ожидаю NSArray).

Соответствующий код должен быть

[yourItemsArray objectAtIndex:indexPath.row];

Edit:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = [keys objectAtIndex:indexPath.section];
    NSArray *nameSection = [names objectForKey:key];
    NSString *rowTitle = [nameSection objectAtIndex:indexPath.row];
    NSLog(@"rowTitle = %@", rowTitle);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...