Пользовательский арабский DatePicker в UIPickerView - PullRequest
1 голос
/ 16 июня 2011

Я пытаюсь реализовать арабский указатель даты. после небольшого исследования (и ничего не нашел) я нашел это как единственное решение: (я прав?)

создать пользовательский UIPickerView с 3 компонентами для дней, месяцев и лет.

реальная проблема в том, что я хочу установить максимальную дату, например [NSDate date].

Должен ли я все это кодировать, или есть более простой способ сделать это ... все поможет.

Спасибо.

Ответы [ 2 ]

1 голос
/ 20 июня 2011

Поскольку предложенный подход madhu не был общим, я наконец-то сделал свой собственный арабский сборщик дат.

Это файлы .h и .m, которые могут кому-то когда-нибудь помочь ... экземпляр этих файлов добавляется как подпредставление к другому представлению, содержащему различные другие типы ячеек.

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

dateCell.h:

#import <UIKit/UIKit.h>


@interface dateCell : UIViewController<UIActionSheetDelegate,UIPickerViewDelegate,UIPickerViewDataSource> {

    IBOutlet UILabel *l;
    IBOutlet UITextField *t;
    IBOutlet UIButton *b;

    UIPickerView *picker;
    UIActionSheet *actionSheet;

    NSDictionary *numbers;
    NSDictionary *months;
    int year;
    int month;
    int day;

    //properties
    NSString *str;
    NSString *name;
    NSString *limit;
    BOOL save;

}

@property (nonatomic, retain) IBOutlet UILabel *l;
@property (nonatomic, retain) IBOutlet UITextField *t;
@property (nonatomic, retain) IBOutlet UIButton *b;

@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *limit;
@property (nonatomic) BOOL save;
@property (nonatomic, retain) UIView* target;
@property (nonatomic, retain) NSDictionary *numbers;
@property (nonatomic, retain) NSDictionary *months;
@property (nonatomic, retain) UIPickerView *picker;
@property (nonatomic, retain) UIActionSheet *actionSheet;

-(IBAction) bPressed;
-(void) setTarget:(UIView *)tar;
-(void)showPicker;
-(int)getYear;
-(NSString*)translateYear:(int)iYear;
-(int) getDay;
-(int) getMonth;
-(int)getNumberOfDaysinYear:(int)y andMonth:(int)m;
- (void)changeDateInLabel:(id)sender;

@end

dateCell.m:

#import "dateCell.h"


@implementation dateCell
@synthesize l,t,b;
@synthesize name, limit, save,str,target,numbers,months,picker,actionSheet;

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

-(void)loadView{
    [super loadView];
    l.text=str;


    NSArray *aDays=[[[NSArray alloc] initWithObjects:@"١",@"٢",@"٣",@"٤",@"٥",@"٦",@"٧",@"٨",@"٩",@"٠",nil] autorelease];
    NSArray *eDays=[[[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",nil] autorelease];
    numbers=[[NSDictionary alloc] initWithObjects:aDays forKeys:eDays];

    NSArray *aMonths=[[[NSArray alloc] initWithObjects:@"يناير",@"فبراير",@"مارس",@"أبريل",@"مايو",@"يونيو",@"يولي",@"أغسطس",@"سبتمبر",@"أكتوبر",@"نوفمبر",@"ديسمبر",nil] autorelease];
    NSArray *eMonths=[[[NSArray alloc] initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",nil] autorelease];
    months=[[NSDictionary alloc] initWithObjects:aMonths forKeys:eMonths];

}


- (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];
    [l release];
    [t release];
    [b release];
    [name release];
    [limit release];
    [str release];
    [target release];
    [numbers release];
    [months release];
    [picker release];
    [actionSheet release];
}


/*§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~
                                    Controls
 §~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~*/

-(IBAction) bPressed{
    [self showPicker];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self showPicker];
    [super touchesBegan:touches withEvent:event];
}

/*§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~
                                    picker handeling methods
 §~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~*/

-(void) setTarget:(UIView *)tar{
    target=tar;
}

-(void)showPicker{
    actionSheet = [[UIActionSheet alloc] initWithTitle:@"select a date"
                                              delegate:self
                                     cancelButtonTitle:nil
                                destructiveButtonTitle:nil
                                     otherButtonTitles:nil];

    picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,40,0,0)];
    picker.delegate = self;
    picker.showsSelectionIndicator = YES;
    year=[self getYear];
    month=[self getMonth];
    day=[self getDay];
    [picker selectRow:year inComponent:0 animated:NO];
    [picker selectRow:(day+(9300/2)) inComponent:2 animated:NO];
    [picker selectRow:(month-1+(9600/2)) inComponent:1 animated:NO];
    [actionSheet addSubview:picker];

    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"OK"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:closeButton];
    [closeButton release];

    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
    [actionSheet setBounds:CGRectMake(0,0,320,469)];
    actionSheet.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin
    |UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin;
    [picker release];
    [actionSheet release];  
}


- (void)changeDateInLabel:(id)sender{
    NSString *m = [[[NSString alloc] initWithFormat:@"%d", (month-1)] autorelease];
    m=[months objectForKey:m];
    NSString *y=[self translateYear:year];
    NSString *d=[self translateYear:day];
    NSString *dat = [NSString stringWithFormat:@"%@ / %@ / %@",d,m,y];
    t.text=dat;

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSString *realStr=[[[NSString alloc] initWithFormat:@"%d-%d-%d",year,month,day+1]autorelease];
    NSDate *realDate = [df dateFromString:realStr];
    [df release];
    NSLog(@"Date: %@", realDate);
    NSString *timestamp = [NSString stringWithFormat:@"%0.0f", [realDate timeIntervalSince1970]];
    NSLog(@"millis: %@", timestamp);
}


-(void)dismissActionSheet{
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}


/*§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~
                                    Date Methods
 §~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~*/

-(int) getYear{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    return [components year];
}

-(NSString*)translateYear:(int)iYear{
    NSString *aYear=@"";
    while(iYear>0){
        int r=iYear%10;
        iYear=iYear/10;
        NSString *s = [NSString stringWithFormat:@"%d", r];
        NSString *temp=[numbers objectForKey:s];
        aYear=[temp stringByAppendingString:aYear];
    }
    return aYear;
}

-(int) getDay{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    return [components day];    
}

-(int) getMonth{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    return [components month];  
}

-(int)getNumberOfDaysinYear:(int)y andMonth:(int)m{
    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents* comps = [[[NSDateComponents alloc] init] autorelease];

    [comps setMonth:m];
    [comps setYear:y];

    NSRange range = [cal rangeOfUnit:NSDayCalendarUnit
                              inUnit:NSMonthCalendarUnit
                             forDate:[cal dateFromComponents:comps]];
    return range.length;
}


/*§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~
                                picker delegate methods
 §~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~§~*/

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;{
    return 3;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    int d=[self getDay];
    int y=[self getYear];
    int m=[self getMonth];
    day=[picker selectedRowInComponent:2]%31;
    if(day==0){
        day=31;
    }
    month=([picker selectedRowInComponent:1]%12)+1;
    year=[picker selectedRowInComponent:0];
    if(year>y){
        year=y;
        [picker selectRow:y inComponent:0 animated:YES];
        [picker selectRow:(d+(9300/2)) inComponent:2 animated:YES];
        [picker selectRow:(m-1+(9600/2)) inComponent:1 animated:YES];
    }
    else{
        if(month>m && year==y){
            month=m;
            [picker selectRow:(m-1+(9600/2)) inComponent:1 animated:YES];
            [picker selectRow:(d+(9300/2)) inComponent:2 animated:YES];
        }
        else{
            int total=[self getNumberOfDaysinYear:year andMonth:month];
            if((day>total)||(day>d && month==m && year==y)){
                day=d;
                [picker selectRow:(d+(9300/2)) inComponent:2 animated:YES];
            }
        }
    }
    [picker reloadComponent:0];
    [picker reloadComponent:1];
    [picker reloadComponent:2];
    [self changeDateInLabel:nil];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (component) {
        case 0:{
            return 4000;
            break;
        }
        case 1:{
            return 12*800;
            break;
        }
        case 2:{
             return 31*300;
            break;  
        }
        default:{
            return 0;
            break;
        }
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *pickerLabel = (UILabel *)view;
    if ((pickerLabel == nil) || ([pickerLabel class] != [UILabel class])) { //newlabel
        CGRect frame = CGRectMake(0.0, 0.0, 75, 32.0);
        pickerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
        pickerLabel.textAlignment = UITextAlignmentRight;
        pickerLabel.backgroundColor = [UIColor clearColor];
        pickerLabel.font = [UIFont boldSystemFontOfSize:22];
    } 
    switch (component) {
        case 0:{
            [pickerLabel setText:[self translateYear:row]];         
            int y=[self getYear];
            if(row==y){
                pickerLabel.textColor = [UIColor blueColor];
            }
            else{
                if(row>y){
                    pickerLabel.textColor = [UIColor grayColor];
                }
                else{
                    pickerLabel.textColor = [UIColor blackColor];
                }
            }
            return pickerLabel;
            break;
        }
        case 1:{
            NSString *sM = [NSString stringWithFormat:@"%d", (row%12)];
            [pickerLabel setText:[months objectForKey:sM]];
            int m=[self getMonth];
            int y=[self getYear];
            if(y<=year){
                if(((row%12)+1)==m){
                    pickerLabel.textColor = [UIColor blueColor];
                }
                else{
                    if(((row%12)+1)>m){
                        pickerLabel.textColor = [UIColor grayColor];
                    }
                    else{
                        pickerLabel.textColor = [UIColor blackColor];
                    }
                }
            }
            else{
                if(year<y){
                    if(((row%12)+1)==m){
                        pickerLabel.textColor = [UIColor blueColor];
                    }
                    else{
                        pickerLabel.textColor = [UIColor blackColor];
                    }
                }
            }
            return pickerLabel;
            break;
        }
        case 2:{
            int r;
            if((row%31)==0){
                r=31;
            }
            else{
                r=(row%31);
            }
            [pickerLabel setText:[self translateYear:r]];
            int d=[self getDay];
            int y=[self getYear];
            int m=[self getMonth];
            if(y<=year && m<=month){
                if(r==d){
                    pickerLabel.textColor = [UIColor blueColor];
                }
                else{
                    if(r>d){
                        pickerLabel.textColor = [UIColor grayColor];
                    }
                    else{
                        int total=[self getNumberOfDaysinYear:year andMonth:month];
                        if(r<=total){
                            pickerLabel.textColor = [UIColor blackColor];
                        }
                        else{
                            pickerLabel.textColor = [UIColor grayColor];
                        }
                    }
                }
            }
            else{
                if(year<y || month<m){
                    if(r==d){
                        pickerLabel.textColor = [UIColor blueColor];
                    }
                    else{
                        int total=[self getNumberOfDaysinYear:year andMonth:month];
                        if(r<=total){
                            pickerLabel.textColor = [UIColor blackColor];
                        }
                        else{
                            pickerLabel.textColor = [UIColor grayColor];
                        }
                    }
                }
            }
            return pickerLabel;
            break;  
        }
    }
    return nil;
}




@end

Спасибо.

0 голосов
/ 16 июня 2011

С http://developer.apple.com/library/ios/#documentation/uikit/reference/UIDatePicker_Class/Reference/UIDatePicker.html:

UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:@"Date Picker" 
                                              delegate:self
                                     cancelButtonTitle:@"Cancel"
                                destructiveButtonTitle:nil
                                     otherButtonTitles:nil];

// Add the picker
UIDatePicker *pickerView = [[UIDatePicker alloc] init];
pickerView.datePickerMode = UIDatePickerModeDate;

//urmindate,urmaxdate are NSDate objects
[pickerView setMinimumDate:urmindate];

[pickerView setMinimumDate:urmaxdate];

[menu addSubview:pickerView];
[menu showInView:self.view];        
[menu setBounds:CGRectMake(0,0,320, 500)];

CGRect pickerRect = pickerView.bounds;
pickerRect.origin.y = -100;
pickerView.bounds = pickerRect;

[pickerView release];
[menu release];

С http://developer.apple.com/library/mac/#documentation/cocoa/reference/Foundation/Classes/NSLocale_Class/Reference/Reference.html:

Свойство locale (и все остальные свойства формата, специфичные для данной страны) по умолчанию равно значению, возвращаемому currentLocale, которое, в свою очередь, зависит от настроек страны iphone, а не языковых настроек. Вам необходимо установить соответствующую страну в общих настройках iphone.

...