尝试在用户选择时检索UITableView单元格的内容

时间:2010-04-07 20:55:11

标签: ios objective-c iphone uitableview cocoa-touch

我已经设置了一个基于UITableView的应用程序,它有一个用于保存数据的.plist。 .plist以字典为根,后跟一些数组,每个数组都包含表中显示的数据字符串。

一切正常,直到我选择一行。我已经设置好了,所以我得到一个关于按下按钮结果的警报,我想在这里查看正在生成的单元格的内容。而不是预期的字符串,例如“数据行1”,我得到的只是该部分中的行号。我已经向前和向前走了但是似乎没有到达任何地方,虽然我确信它很简单。

代码编译得很好,没有任何警告或错误,如果我能得到所选单元格的字符串,我将很顺利,所以任何帮助都会受到赞赏。我知道我需要在NSUInteger row = [indexPath row];之后做更多的事情,但那是我的思绪枯竭的地方......

以下是相关的“选择”部分,如果我需要发布更多代码请告诉我,我非常感谢您对此提供任何帮助...(请原谅我的“提醒”消息,我很高兴从行选择中得到SOMETHING!)

- (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 个答案:

答案 0 :(得分:2)

该方法只传递给你的任何数据源的索引号,因此请将其引用回用于UITableView单元的数据源(我希望有一个NSArray)。

相关代码应为

[yourItemsArray objectAtIndex:indexPath.row];

编辑:

- (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];
}