0

我正在尝试在表格上实现索引,因为我使用以下方法索引出现在右侧,但它不起作用代码如下

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 2;
    }

    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

        NSArray *toBeReturned = [NSArray arrayWithArray:
                                 [@"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
                                  componentsSeparatedByString:@"|"]];

        return toBeReturned;
    }


   - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

    int foundIndex = 0;


    for (int i = 0; i< [mainArray count]; i++) {
        // Here you return the name i.e. Honda,Mazda
        // and match the title for first letter of name
        // and move to that row corresponding to that indexpath as below
        NSString *letterString = [[[mainArray valueForKey:@"name"] objectAtIndex:i] substringToIndex:1];

        NSLog(@"letterString%@",letterString);
        NSLog(@"title%@",title);

        if ([[letterString uppercaseString ] compare:title] == NSOrderedDescending){
            break;
            foundIndex++;        }

        if(foundIndex > mainArray.count)
            foundIndex = mainArray.count;
        [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        return 1;

    }
  }

   - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

            return 120;


    }
    - (UITableViewCell *)tableView:(UITableView *)tableView

             cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
       //—set the text to display for the cell—

        NSLog(@"%d",mainArray.count);
        NSLog(@"%@",mainArray);

        UIImageView *selectionView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 120)];

        UIImage *image = [UIImage imageNamed:@"default.png"];
        UIImageView* blockView = [[UIImageView alloc] initWithImage:image];
        blockView.layer.cornerRadius = 4;
        blockView.layer.masksToBounds = YES;
        blockView.layer.borderWidth = 2;
        blockView.layer.borderColor = [UIColor blackColor].CGColor;

        blockView.frame = CGRectMake(5, 5, 110, 110);

      //  title isKindOfClass:[NSNull class]])
        //NSLog(@"%@",[[mainArray valueForKey:@"image"] objectAtIndex:[indexPath row]]);


        id obj = [[mainArray valueForKey:@"image"] objectAtIndex:[indexPath row]];
        if ([obj isKindOfClass:[NSString class]])
        {

            [selectionView addSubview:blockView];
        }

        else     {

            UIImage *contactImage = [[UIImage alloc]init];
            contactImage = [[mainArray valueForKey:@"image"] objectAtIndex:[indexPath row]];
            //  NSLog(@"  array%@",[[mainArray valueForKey:@"image"] objectAtIndex:[indexPath row]]);
            NSLog(@" image%@",contactImage);
            UIImageView *blockView = [[UIImageView alloc] initWithImage:contactImage];
            blockView.frame = CGRectMake(5, 5, 110, 110);
            blockView.layer.cornerRadius = 4;
            blockView.layer.masksToBounds = YES;
            blockView.layer.borderWidth = 2;
            blockView.layer.borderColor = [UIColor blackColor].CGColor;

            [selectionView addSubview:blockView];
        }

        NSLog(@" name :%@",[[mainArray valueForKey:@"name"] objectAtIndex:[indexPath row]]);

        if ([[[mainArray valueForKey:@"name"] objectAtIndex:[indexPath row]] isEqualToString:@"(null)"]) {
            UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
            name.text =@"Name Not Available";
            [name setBackgroundColor:[UIColor clearColor]];
            [ name setFont:[UIFont fontWithName:@"Arial-BoldMT" size:30]];
            name.textColor = [UIColor whiteColor];
            [selectionView addSubview:name];
               }
        else{

            UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
            name.text =[[mainArray valueForKey:@"name"] objectAtIndex:[indexPath row]];
            [name setBackgroundColor:[UIColor clearColor]];
            [ name setFont:[UIFont fontWithName:@"Arial-BoldMT" size:30]];
            name.textColor = [UIColor whiteColor];
            [selectionView addSubview:name];
        }

        if ([[[mainArray valueForKey:@"phone"] objectAtIndex:[indexPath row]] isEqualToString:@"Add Number"]) {

            UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
            phone.text =@"Not Available";
            [phone setBackgroundColor:[UIColor clearColor]];
            [ phone setFont:[UIFont fontWithName:@"Arial-BoldMT" size:25]];
            phone.textColor = [UIColor whiteColor];
            [selectionView addSubview:phone];
        }
        else{

            UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
            phone.text =[[mainArray valueForKey:@"phone"] objectAtIndex:[indexPath row]];
            [phone setBackgroundColor:[UIColor clearColor]];
            [ phone setFont:[UIFont fontWithName:@"Arial-BoldMT" size:25]];
            phone.textColor = [UIColor whiteColor];
            [selectionView addSubview:phone];

        }
        if ([[[mainArray valueForKey:@"email"] objectAtIndex:[indexPath row]] isEqualToString:@"Add Email"]) {

            UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
            email.text =@"Email Id Not Available";
            [email setBackgroundColor:[UIColor clearColor]];
            [ email setFont:[UIFont fontWithName:@"Arial-BoldMT" size:20]];
            email.textColor = [UIColor whiteColor];
            [selectionView addSubview:email];
        }
        else{

            UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
            email.text =[[mainArray valueForKey:@"email"] objectAtIndex:[indexPath row]];
            [email setBackgroundColor:[UIColor clearColor]];
            [ email setFont:[UIFont fontWithName:@"Arial-BoldMT" size:20]];
            email.textColor = [UIColor whiteColor];
            [selectionView addSubview:email];

        }

         [[cell contentView] addSubview:selectionView];
         return cell;
    }

当我单击任何索引而不是正确的索引时,我面临的问题是它到达表的顶部

4

3 回答 3

1

要使用索引,您的表应该真正分成几个部分。看起来目前您正在要求框架滚动到指定的行,然后立即滚动到第 0 节的顶部。

如果您performSelector在短暂延迟后请求滚动,它可能会起作用(它可能看起来很讨厌)。或者如果您从该方法返回 -1 (文档不支持这种猜测)。

答案实际上是使用表格中的部分并让框架按设计工作。

于 2013-08-14T06:20:42.727 回答
0
.h

#import <TapkuLibrary/TapkuLibrary.h>

#import <UIKit/UIKit.h>

#import <EventKit/EventKit.h>




@interface CalendarMonthViewController : TKCalendarMonthTableViewController{

    NSMutableArray *events;
    EKEventStore *eventStore;

    NSDate *startDatee;
    NSDate *lastDatee;
}

@property (strong,nonatomic) NSMutableArray *dataArray;
@property (strong,nonatomic) NSMutableDictionary *dataDictionary;

- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end;

@end

.m

#import "CalendarMonthViewController.h"
#import "AppDelegate.h"


@implementation CalendarMonthViewController

#pragma mark - View Lifecycle


- (void) viewDidLoad{
    [super viewDidLoad];

    [self.monthView selectDate:[NSDate month]];
   }
-(void)viewWillAppear:(BOOL)animated{
    [self updateTableOffset:YES];

    NSLog(@"hi ha ");


   }

-(void)fatchAllEvent{


    eventStore = [[EKEventStore alloc] init];

    if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
    {
        __block typeof (self) weakSelf = self; // replace __block with __weak if you are using ARC
        dispatch_async(dispatch_get_main_queue(), ^{
                  [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
         {

             if (granted)
             {
                 NSLog(@" granted");

                 [weakSelf performSelectorOnMainThread:@selector(allCalendarEvent) withObject:nil waitUntilDone:YES];
             }
             else
             {
                 NSLog(@"Not granted");
             }
         }];

               });
    }
    else
    {
        [self allCalendarEvent];
    }


}

-(void)allCalendarEvent{

    NSDate *startDate = [NSDate distantPast];
    NSDate *endDate = [NSDate distantFuture];

    // use Dictionary for remove duplicates produced by events covered more one year segment
    NSMutableDictionary *eventsDict = [NSMutableDictionary dictionaryWithCapacity:1024];

    NSDate* currentStart = [NSDate dateWithTimeInterval:0 sinceDate:startDate];

    int seconds_in_year = 60*60*24*365;

    // enumerate events by one year segment because iOS do not support predicate longer than 4 year !
    while ([currentStart compare:endDate] == NSOrderedAscending) {

        NSDate* currentFinish = [NSDate dateWithTimeInterval:seconds_in_year sinceDate:currentStart];

        if ([currentFinish compare:endDate] == NSOrderedDescending) {
            currentFinish = [NSDate dateWithTimeInterval:0 sinceDate:endDate];
        }
        NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:currentStart endDate:currentFinish calendars:nil];
        [eventStore enumerateEventsMatchingPredicate:predicate
                                          usingBlock:^(EKEvent *event, BOOL *stop) {

                                              if (event) {
                                                  [eventsDict setObject:event forKey:event.eventIdentifier];
                                              }

                                          }];
        currentStart = [NSDate dateWithTimeInterval:(seconds_in_year + 1) sinceDate:currentStart];

    }

    events = [[NSMutableArray alloc]init];

    for (id key in eventsDict) {
        id anObject = [eventsDict objectForKey:key];

        [events addObject:anObject];
        /* Do something with anObject. */
    }




    NSLog(@"all event %@",events);

    CFRunLoopStop(CFRunLoopGetCurrent());

   // NSLog(@"all event  crash%@",events);


}



#pragma mark - MonthView Delegate & DataSource
- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{

    if (!events) {

         [self fatchAllEvent];
         CFRunLoopRun(); 

    }





    NSLog(@"all event %@",events);



    [self generateRandomDataForStartDate:startDate endDate:lastDate];

    // NSLog(@"%@",self.dataDictionary);
     NSLog(@"%@",self.dataArray);
    NSLog(@"%@",self.dataDictionary);
    NSLog(@"%@",[self.dataDictionary allKeys]);
    return self.dataArray;


}
- (void) calendarMonthView:(TKCalendarMonthView*)monthView didSelectDate:(NSDate*)date{

    // CHANGE THE DATE TO YOUR TIMEZONE
    TKDateInformation info = [date dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDate *myTimeZoneDay = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone systemTimeZone]];

    NSLog(@"Date Selected: %@",myTimeZoneDay);

    [self.tableView reloadData];
}
- (void) calendarMonthView:(TKCalendarMonthView*)mv monthDidChange:(NSDate*)d animated:(BOOL)animated{
    [super calendarMonthView:mv monthDidChange:d animated:animated];
    [self.tableView reloadData];
}


#pragma mark - UITableView Delegate & DataSource

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;

}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ([[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad)
    {
        NSArray *views =[[NSBundle mainBundle] loadNibNamed:@"CalendarTableHeader" owner:nil options:nil];
        UIView *headerView=[views objectAtIndex:0];
        return headerView;
    }
    else
    {
        return nil;
    }
}

- (CGFloat) tableView:(UITableView *) tableView heightForHeaderInSection:(NSInteger) section {
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        return 25;
    } else {
        return 0;
    }
}


- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
    if(ar == nil) return 0;
    return [ar count];
}
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];



    NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
    cell.textLabel.text = [ar objectAtIndex:indexPath.row];

    return cell;

}

- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
    return [date compare:firstDate] == NSOrderedDescending &&
    [date compare:lastDate]  == NSOrderedAscending;
}


- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end{
    // this function sets up dataArray & dataDictionary
    // dataArray: has boolean markers for each day to pass to the calendar view (via the delegate function)
    // dataDictionary: has items that are associated with date keys (for tableview)


    NSMutableArray *arrayOfDates = [[NSMutableArray alloc   ]init];
     NSMutableArray *arrayOfNames = [[NSMutableArray alloc   ]init];



//  NSLog(@"Delegate Range: %@ %@ %d",start,end,[start daysBetweenDate:end]);


    NSDateFormatter *newformater=[[[NSDateFormatter alloc]init]autorelease];
    [newformater setDateFormat:@"yyyy-MM-dd HH:mm:ss "];

    NSDate *startD = [newformater dateFromString:[newformater stringFromDate:start]];
    NSDate *endD = [newformater dateFromString:[newformater stringFromDate:end]];

    NSLog(@"%@",events);


    BOOL isAttempt = NO;

    for (int i =0; i<arrayOfDates.count; i++) {

        if ([start isEqualToDate:[arrayOfDates objectAtIndex:i]]) {

            [self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:start];

            [self.dataArray addObject:[NSNumber numberWithBool:YES]];
            isAttempt = YES;

        }
        else{

            isAttempt = NO;
        }

    }

    if (!isAttempt) {

        [self.dataArray addObject:[NSNumber numberWithBool:NO]];
    }



    for (int i = 0; i<events.count; i++) {



        NSDate *eventDate = [[events valueForKey:@"startDate"] objectAtIndex:i];
        NSString *eventName = [[events valueForKey:@"title"]objectAtIndex:i];

        NSLog(@"startreal%@",start);
        NSLog(@"endreal%@",end);

        NSLog(@"eventName:::%@",eventName);

        NSLog(@"start%@",startD);
        NSLog(@"end%@",endD);
         NSLog(@"eventDate%@",eventDate);


        if([self isDate:eventDate inRangeFirstDate:startD lastDate:endD]){



            [arrayOfDates addObject:eventDate];
            [arrayOfNames addObject:eventName];


        }else{


    }
    }



    NSLog(@"eventdate = %@",arrayOfDates);
    NSLog(@"eventName = %@",arrayOfNames);




    // the dates that we have will go thorought for loop and we wil check if its between start and end date then we will add that object to datadictionary or wont

    [self.dataArray removeAllObjects];
    [self.dataDictionary removeAllObjects];

    self.dataArray = [NSMutableArray array];
    self.dataDictionary = [NSMutableDictionary dictionary];



    NSDate *d = start;


    while(YES){

        BOOL isAttempt = NO;

        for (int i =0; i<arrayOfDates.count; i++) {

            if ([d isEqualToDate:[arrayOfDates objectAtIndex:i]]) {

                [self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:d];

                 [self.dataArray addObject:[NSNumber numberWithBool:YES]];
                isAttempt = YES;

            }
            else{

                isAttempt = NO;
            }

        }

    if (!isAttempt) {

        [self.dataArray addObject:[NSNumber numberWithBool:NO]];
    }



        TKDateInformation info = [d dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        info.day++;
        d = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

        if([d compare:end]==NSOrderedDescending) break;
    }


}


-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [self updateTableOffset:YES];
}


- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}


@end
于 2013-08-14T13:39:39.600 回答
0

当我们有第 0 部分时,我们可以这样做

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

        NSArray *toBeReturned = [NSArray arrayWithArray:
                                 [@"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z"
                                  componentsSeparatedByString:@"|"]];

        return toBeReturned;
    }

    - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

        int foundIndex = 0;


        for (int i = 0; i< [mainArray count]; i++) {

            NSString *letterString = [[[mainArray valueForKey:@"name"] objectAtIndex:i] substringToIndex:1];

            NSLog(@"letterString%@",letterString);
            NSLog(@"title%@",title);

            if ([letterString caseInsensitiveCompare:title] == NSOrderedSame)


          {

               break;


            }

            else{


                foundIndex++;

                NSLog(@"founded index %d",foundIndex);


            }
        }

        NSLog(@"founded index %d",mainArray.count);

        NSLog(@"founded index %d",foundIndex);

        if(foundIndex >= mainArray.count){


             foundIndex = mainArray.count-1;

        }

        NSLog(@"founded index %d",foundIndex);


            [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            return 1;


      }
于 2013-08-14T06:50:42.393 回答