简体   繁体   中英

How to get the position of a particular date when the date is selected in calender,ios

Am getting confused here.I had implemented a calender control in ios application.But not able to find the position of a particular date when the user selects the date.How to find the position of a particular date which is selected by the user?Please some one help me or give me some advice.Provide any sample codes.Great answers would be appreciated.

In DayButton.h

//
//  DayButton.h
//  DDCalendarView
//
//
//

#import <UIKit/UIKit.h>

@protocol DayButtonDelegate <NSObject>
- (void)dayButtonPressed:(id)sender;
@end

@interface DayButton : UIButton {
    id <DayButtonDelegate> delegate;
    NSDate *buttonDate;
}

@property (nonatomic, assign) id <DayButtonDelegate> delegate;
@property (nonatomic, copy) NSDate *buttonDate;

- (id)buttonWithFrame:(CGRect)buttonFrame;

@end

In DayButton.m

//
//  DayButton.m
//  DDCalendarView
//
//

#import "DayButton.h"


@implementation DayButton
@synthesize delegate, buttonDate;

- (id)buttonWithFrame:(CGRect)buttonFrame {
    self = [DayButton buttonWithType:UIButtonTypeCustom];

    self.frame = buttonFrame;
    self.titleLabel.textAlignment = UITextAlignmentRight;
    self.backgroundColor = [UIColor clearColor];
    [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

    [self addTarget:delegate action:@selector(dayButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    UILabel *titleLabel = [self titleLabel];
    CGRect labelFrame = titleLabel.frame;
    int framePadding = 4;
    labelFrame.origin.x = self.bounds.size.width - labelFrame.size.width - framePadding;
    labelFrame.origin.y = framePadding;

    [self titleLabel].frame = labelFrame;
}

- (void)dealloc {
    [super dealloc];
}


@end

In DDCalenderView.h

//
//  DDCalendarView.h
//  DDCalendarView
//
//

#import <UIKit/UIKit.h>
#import "DayButton.h"

@protocol DDCalendarViewDelegate <NSObject>
- (void)dayButtonPressed:(DayButton *)button;

@optional
- (void)prevButtonPressed;
- (void)nextButtonPressed;

@end

@interface DDCalendarView : UIView <DayButtonDelegate> {
    id <DDCalendarViewDelegate> delegate;
    NSString *calendarFontName;
    UILabel *monthLabel;
    NSMutableArray *dayButtons;
    NSCalendar *calendar;
    float calendarWidth;
    float calendarHeight;
    float cellWidth;
    float cellHeight;
    int currentMonth;
    int currentYear;
}

@property(nonatomic, assign) id <DDCalendarViewDelegate> delegate;

- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName delegate:(id)theDelegate;
- (void)updateCalendarForMonth:(int)month forYear:(int)year;
- (void)drawDayButtons;
- (void)prevBtnPressed:(id)sender;
- (void)nextBtnPressed:(id)sender;

@end

In DDCalenderView.m

//
//  DDCalendarView.m
//  DDCalendarView
//
//

#import "DDCalendarView.h"

@implementation DDCalendarView
@synthesize delegate;

- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName delegate:(id)theDelegate {
    if ((self = [super initWithFrame:frame])) {
        self.delegate = theDelegate;

        //Initialise vars
        calendarFontName = fontName;
        calendarWidth = frame.size.width;
        calendarHeight = frame.size.height;
        cellWidth = frame.size.width / 7.0f;
        cellHeight = frame.size.height / 14.0f;

        //View properties
//      UIColor *bgPatternImage = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"square-paper.png"]];
//       
//      self.backgroundColor = bgPatternImage;
//      [bgPatternImage release];



        //Set up the calendar header


        self.backgroundColor=[UIColor whiteColor];

        UIButton *prevBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [prevBtn setImage:[UIImage imageNamed:@"left-arrow.png"] forState:UIControlStateNormal];
        prevBtn.frame = CGRectMake(0, 0, cellWidth, cellHeight);
        [prevBtn addTarget:self action:@selector(prevBtnPressed:) forControlEvents:UIControlEventTouchUpInside];

        UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [nextBtn setImage:[UIImage imageNamed:@"right-arrow.png"] forState:UIControlStateNormal];
        nextBtn.frame = CGRectMake(calendarWidth - cellWidth, 0, cellWidth, cellHeight);
        [nextBtn addTarget:self action:@selector(nextBtnPressed:) forControlEvents:UIControlEventTouchUpInside];

        CGRect monthLabelFrame = CGRectMake(cellWidth, 0, calendarWidth - 2*cellWidth, cellHeight);
        monthLabel = [[UILabel alloc] initWithFrame:monthLabelFrame];
        monthLabel.font = [UIFont fontWithName:calendarFontName size:18];
        monthLabel.textAlignment = UITextAlignmentCenter;
        monthLabel.backgroundColor = [UIColor clearColor];
        monthLabel.textColor = [UIColor blackColor];

        //Add the calendar header to view       
        [self addSubview: prevBtn];
        [self addSubview: nextBtn];
        [self addSubview: monthLabel];

        //Add the day labels to the view
        char *days[7] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
        for(int i = 0; i < 7; i++) {
            CGRect dayLabelFrame = CGRectMake(i*cellWidth, cellHeight, cellWidth, cellHeight);
            UILabel *dayLabel = [[UILabel alloc] initWithFrame:dayLabelFrame];
            dayLabel.text = [NSString stringWithFormat:@"%s", days[i]];
            dayLabel.textAlignment = UITextAlignmentCenter;
            dayLabel.backgroundColor = [UIColor clearColor];
            dayLabel.font = [UIFont fontWithName:calendarFontName size:16];
            dayLabel.textColor = [UIColor darkGrayColor];

            [self addSubview:dayLabel];
            [dayLabel release];
        }

        [self drawDayButtons];

        //Set the current month and year and update the calendar
        calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

        NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
        NSDateComponents *dateParts = [calendar components:unitFlags fromDate:[NSDate date]];
        currentMonth = [dateParts month];
        currentYear = [dateParts year];

        [self updateCalendarForMonth:currentMonth forYear:currentYear];

    }
    return self;
}

- (void)drawDayButtons {
    dayButtons = [[NSMutableArray alloc] initWithCapacity:42];
    for (int i = 0; i < 6; i++) {
        for(int j = 0; j < 7; j++) {
            CGRect buttonFrame = CGRectMake(j*cellWidth, (i+2)*cellHeight, cellWidth, cellHeight);
            DayButton *dayButton = [[DayButton alloc] buttonWithFrame:buttonFrame];
            dayButton.titleLabel.font = [UIFont fontWithName:calendarFontName size:14];
            dayButton.delegate = self;

            [dayButtons addObject:dayButton];
            [dayButton release];

            [self addSubview:[dayButtons lastObject]];
        }
    }
}

- (void)updateCalendarForMonth:(int)month forYear:(int)year {
    char *months[12] = {"January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"};
    monthLabel.text = [NSString stringWithFormat:@"%s %d", months[month - 1], year];

    //Get the first day of the month
    NSDateComponents *dateParts = [[NSDateComponents alloc] init];
    [dateParts setMonth:month];
    [dateParts setYear:year];
    [dateParts setDay:1];
    NSDate *dateOnFirst = [calendar dateFromComponents:dateParts];
    [dateParts release];
    NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:dateOnFirst];
    int weekdayOfFirst = [weekdayComponents weekday];   

    //Map first day of month to a week starting on Monday
    //as the weekday component defaults to 1->Sun, 2->Mon...
    if(weekdayOfFirst == 1) {
        weekdayOfFirst = 7;
    } else {
        --weekdayOfFirst;
    }

    int numDaysInMonth = [calendar rangeOfUnit:NSDayCalendarUnit 
                                        inUnit:NSMonthCalendarUnit 
                                            forDate:dateOnFirst].length;

    int day = 1;
    for (int i = 0; i < 6; i++) {
        for(int j = 0; j < 7; j++) {
            int buttonNumber = i * 7 + j;

            DayButton *button = [dayButtons objectAtIndex:buttonNumber];

            button.enabled = NO; //Disable buttons by default
            [button setTitle:nil forState:UIControlStateNormal]; //Set title label text to nil by default
            [button setButtonDate:nil];

            if(buttonNumber >= (weekdayOfFirst - 1) && day <= numDaysInMonth) {
                [button setTitle:[NSString stringWithFormat:@"%d", day] 
                                                forState:UIControlStateNormal];

                NSDateComponents *dateParts = [[NSDateComponents alloc] init];
                [dateParts setMonth:month];
                [dateParts setYear:year];
                [dateParts setDay:day];
                NSDate *buttonDate = [calendar dateFromComponents:dateParts];
                [dateParts release];
                [button setButtonDate:buttonDate];

                button.enabled = YES;
                ++day;
            }
        }
    }
}

- (void)prevBtnPressed:(id)sender {
    if(currentMonth == 1) {
        currentMonth = 12;
        --currentYear;
    } else {
        --currentMonth;
    }

    [self updateCalendarForMonth:currentMonth forYear:currentYear];

    if ([self.delegate respondsToSelector:@selector(prevButtonPressed)]) {
        [self.delegate prevButtonPressed];
    }
}

- (void)nextBtnPressed:(id)sender {
    if(currentMonth == 12) {
        currentMonth = 1;
        ++currentYear;
    } else {
        ++currentMonth;
    }

    [self updateCalendarForMonth:currentMonth forYear:currentYear];

    if ([self.delegate respondsToSelector:@selector(nextButtonPressed)]) {
        [self.delegate nextButtonPressed];
    }
}

- (void)dayButtonPressed:(id)sender {
    DayButton *dayButton = (DayButton *) sender;
    [self.delegate dayButtonPressed:dayButton];
}

- (void)dealloc {
    [calendar release];
    [dayButtons release];
    [super dealloc];
}


@end

In MainViewController.h

//
//  MainViewController.h
//  DDCalendarView
//
//

#import <UIKit/UIKit.h>
#import "DDCalendarView.h"

@interface MainViewController : UIViewController <DDCalendarViewDelegate> {
    DDCalendarView *calendarView;
}

@end

In MainVIewController.m

//
//  MainViewController.m
//  DDCalendarView
//
//

#import "MainViewController.h"

@implementation MainViewController


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
    UIView *appView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    calendarView = [[DDCalendarView alloc] initWithFrame:appView.bounds fontName:@"AmericanTypewriter" delegate:self];

    self.view = appView;
    [appView release];

    [self.view addSubview: calendarView];
}

- (void)dayButtonPressed:(DayButton *)button {
    //For the sake of example, we obtain the date from the button object
    //and display the string in an alert view
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    NSString *theDate = [dateFormatter stringFromDate:button.buttonDate];
    [dateFormatter release];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterLongStyle];
    NSString *theDate = [dateFormatter stringFromDate:button.buttonDate];
    [dateFormatter release];

    //  UIAlertView *dateAlert = [[UIAlertView alloc]
    //                              initWithTitle:@"Date Pressed"
    //                              message:theDate 
    //                              delegate:self
    //                              cancelButtonTitle:@"Ok"
    //                              otherButtonTitles:nil];
    //  [dateAlert show];
    //  [dateAlert release];
    //    


timeEntry *time=[[timeEntry alloc]init];
[time setDate:theDate];
[self.navigationController pushViewController:time animated:YES];
[time release];

}

- (void)nextButtonPressed {
    NSLog(@"Next...");
}

- (void)prevButtonPressed {
    NSLog(@"Prev...");
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

I took an image above the calender.If the user selects the date,the image has to move to that date in horizontal or vertical position.Is Animation necessary?If yes,how to handle or otherwise can anyone help in their own manner.Please.Great answers would be appreciated.

Have you ever tried Tapku library ? Its preferable for custom calender controls. Hope this helps you.

I would recommend using Kal . I use it for a month view and it works great. It keeps track of the date even when you move to another view.

EDIT: get the location of the tap check out this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM