Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 仅在文本字段中键入日期_Objective C_Xcode_Nsstring - Fatal编程技术网

Objective c 仅在文本字段中键入日期

Objective c 仅在文本字段中键入日期,objective-c,xcode,nsstring,Objective C,Xcode,Nsstring,有没有办法确保用户只能在文本字段中输入日期?例如,字符0-9和/(或更好的解决方案)?如果是这样,最好的方法是什么 我没有成功 NSString*LEGAL=@“0123456789/” NSCharacterSet*字符集=[[NSCharacterSet] characterSetWithCharactersInString:LEGAL]InversedSet] NSString*filteredOne=[[firstString] 由字符分隔的组件集合:字符集] 组件通过字符串连接:@“]

有没有办法确保用户只能在文本字段中输入日期?例如,字符0-9和/(或更好的解决方案)?如果是这样,最好的方法是什么

我没有成功

NSString*LEGAL=@“0123456789/”

NSCharacterSet*字符集=[[NSCharacterSet] characterSetWithCharactersInString:LEGAL]InversedSet]

NSString*filteredOne=[[firstString] 由字符分隔的组件集合:字符集]

组件通过字符串连接:@“]

NSString*filteredTwo=[[secondString] 由字符分隔的组件集合:字符集]

组件通过字符串连接:@“]

firstString=filteredOne

secondString=filteredTwo


如果我没弄错你的问题,我也许能帮上忙。这是我以前用来格式化文本字段以选择日期的一些旧代码。希望您能够理解它并使其适应您的需要:

注:
UITextField*endDate

 //Get date and format it for the textfields
-(void)updateTextField:(id)sender
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];

    UIDatePicker *picker = (UIDatePicker*)self.endDate.inputView;
    NSString *theDate = [dateFormat stringFromDate:picker.date];

    self.endDate.text = [NSString stringWithFormat:@"%@",theDate];

    [dateFormat release];
}
要使用日期选择器而不是键盘,请在viewDidLoad()方法中尝试类似的操作*

*注意,您可能需要自己的NSDate接口/实现,如果需要,代码如下。别忘了在文件顶部导入它

NSDate.h

#import <Foundation/Foundation.h>

@interface NSDate (missingFunctions) 
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
@end

为什么不使用
NSDatePicker
(在OS X上)或
UIDatePicker
(在iOS上)?是的,您可以将文本字段的输入视图设置为UIDatePicker。textField.inputView=日期选择器;或指定NSDateFormatter作为格式化程序
#import <Foundation/Foundation.h>

@interface NSDate (missingFunctions) 
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
@end
#import "NSDate.h"

@implementation NSDate (missingFunctions)

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    return [calendar dateFromComponents:components];
}   
@end