iOS每日一记——————一些常用的小技巧(一)

plist 文件中的数据赋给数组
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];

NSArray *array = [NSArray arrayWithContentsOfFile:thePath];

UITouch手指的触摸范围:64X64

#pragma mark -
#pragma mark Touch Events

- (void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event {originFrame = bookCover.frame;
NSLog(@"%s %d", __FUNCTION__,__LINE__);

if ([touches count] == 2)
{
NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouches objectAtIndex:0];
UITouch *secondTouch = [twoTouches objectAtIndex:1];
CGPoint firstPoint = [firstTouch locationInView:bookCover];CGPoint secondPoint = [secondTouch locationInView:bookCover];

CGFloat deltaX = secondPoint.x - firstPoint.x;
CGFloat deltaY = secondPoint.y - firstPoint.y;initialDistance = sqrt(deltaX * deltaX + deltaY * deltaY );frameX = bookCover.frame.origin.x;
frameY = bookCover.frame.origin.y;
frameW = bookCover.frame.size.width;
frameH = bookCover.frame.size.height;
NSLog(@"%s %d", __FUNCTION__,__LINE__);
}
}

- (void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event {

if([touches count] == 2)
{
NSLog(@"%s %d", __FUNCTION__,__LINE__);

NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouches objectAtIndex:0];UITouch *secondTouch = [twoTouches objectAtIndex:1];

CGPoint firstPoint = [firstTouch locationInView:bookCover];CGPoint secondPoint = [secondTouch locationInView:bookCover];

CGFloat deltaX = secondPoint.x - firstPoint.x;
CGFloat deltaY = secondPoint.y - firstPoint.y;
CGFloat currentDistance = sqrt(deltaX * deltaX + deltaY * deltaY );

if (initialDistance == 0) {
initialDistance = currentDistance;
}
else if (currentDistance != initialDistance)
{
CGFloat changedDistance = currentDistance - initialDistance;NSLog(@"changedDistance = %f",changedDistance);
[bookCover setFrame:CGRectMake(frameX - changedDistance / 2,frameY - (changedDistance * frameH) / (2 * frameW),
frameW + changedDistance,
frameH + (changedDistance * frameH) / frameW)];
}
}
}

- (void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event {UITouch *touch = [touches anyObject];


UITouch 双击图片变大/还原
if ([touch tapCount] == 2)
{
NSLog(@"%s %d", __FUNCTION__,__LINE__);

if (!flag) {
[bookCover setFrame:CGRectMake(bookCover.frame.origin.x - bookCover.frame.size.width / 2,

bookCover.frame.origin.y - bookCover.frame.size.height / 2,2 * bookCover.frame.size.width,
2 * bookCover.frame.size.height)];
flag = YES;

}
else {
[bookCover setFrame:CGRectMake(bookCover.frame.origin.x + bookCover.frame.size.width / 4,bookCover.frame.origin.y + bookCover.frame.size.height / 4,
bookCover.frame.size.width / 2, bookCover.frame.size.height / 2)];
flag = NO;
}
}
}


Get the Location of Touches

(CGPoint)locationInView:(UIView *)view(CGPoint)previousLocationInView:(UIView *)viewview window

Getting Touch Attributes

tapCount(read only) timestamp(read only) phase(read only)

Getting a Touch Object's Gesture RecognizersgestureRecognizers

Touch Phase

UITouchPhaseBegan

UITouchPhaseMoved

UITouchPhaseStationary

UITouchPhaseEnded

UITouchPhaseCancelled

Plist 里读内容
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"];NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];NSString *book = [dictionary objectForKey:bookTitle];
[textView setText:book];

(void) initialize {
NSUserDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"YES"forKey:@"DeleteBackup"];


[defaults registerDefaults:appDefaults];}

To get a value of a default, use the valueForKey: method:[[theDefaultsController values] valueForKey:@"userName"];
To set a value for a default, use setValue:forKey:
[[theDefaultsController values] setValue:newUserName forKey:@"userName"];

[[NSUserDefaults standardUserDefaults] setValue:aVale forKey:aKey];[[NSUserDefaults standardUserDefaults] valueForKey:aKey];


获取 Documents 目录
NSArray *paths = NSSearchPathForDictionariesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [documentsDirectorystringByAppendingPathComponent:@"theFile.txt"];

获取 tmp 目录
NSString *tempPath = NSTemporaryDirectory();
NSString *tempFile = [tempPath stringByAppendingPathComponent:@"tempFile.txt"];

[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"someKey"];[[NSUserDefaults standardUserDefaults] objectForKey:aKey];


自定义 NavigationBar
navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];[navigationBar setBarStyle:UIBarStyleBlackOpaque];

myNavigationItem = [[UINavigationItem alloc] initWithTitle:@"Setting"];[navigationBar setItems:[NSArray arrayWithObject:myNavigationItem]];[self.view addSubview:navigationBar];

backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlaintarget:self action:@selector(back)];
myNavigationItem.leftBarButtonItem = backButton;


利用 UIWebView 显示 pdf 文件、网页。。。
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[webView setDelegate:self];
[webView setScalesPageToFit:YES];
[webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight];
[webView setAllowsInlineMediaPlayback:YES];
[self.view addSubview:webView];
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"ojc" ofType:@"pdf"];NSURL *url = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *request = [NSURLRequest requestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5];
[webView loadRequest:request];

[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURLURLWithString: @"http://www.cnblogs.com/tracy-e/"]]];

NSString *errorString = [NSString stringWithFormat:@"<html><center><font size=+5 color ='red'>An Error Occurred:<br>%@</fone></center></html>",error];[myWebView loadHTMLString:errorString baseURL:nil];

//Stopping a load request when the view is to disappear- (void)viewWillDisappear:(BOOL)animate{
if ([myWebView loading]){
[myWebView stopLoading];

}
myWebView.delegate = nil;
[UIApplication shareApplication].networkActivityIndicatorVisible = NO;}


Handing the Keyboard notifications

//Call this method somewhere in your view controller setup code- (void) registerForKeyboardNotifications{

[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardWasShown:)name:UIKeyboardDidShowNotification
object:nil];

[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardWasHidden:)name:UIKeyboardDidHideNotification
object:nil];

}

//Called when the UIKeyboardDidShowNotification is sent
- (void)keyboardWasShown:(NSNotification *) aNotification{if(keyboardShown)
return;
NSDictionary *info = [aNotification userInfo];

//get the size of the keyboard.
NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];CGSize keyboardSize = [aValue CGRectValue].size;

//Resize the scroll view


CGRect viewFrame = [scrollView frame];viewFrame.size.height -= keyboardSize.height;

//Scroll the active text field into view
CGRect textFieldRect = [activeField frame];
[scrollView scrollRectToVisible:textFieldRect animated:YES];

keyboardShown = YES;}

//Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification *) aNotification{NSDictionary *info = [aNotification userInfo];

//Get the size of the keyboard.
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];CGSize keyboardSize = [aValue CGRectValue].size;

//Reset the height of the scroll view to its original valueCGRect viewFrame = [scrollView Frame];viewFrame.size.height += keyboardSize.height;scrollView.frame = viewFrame;

keyboardShown = NO;}


点击键盘的 next 按钮,在不同的 textField 之间换行//首先给不同的 textField 赋不同的且相邻的 tag
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([textField returnKeyType] != UIReturnKeyDone)
{
NSInteger nextTag = [textField tag] + 1;
UIView *nextTextField = [[self tableView] viewWithTag:nextTag];[nextTextField becomeFirstResponder];
}
else {
[textField resignFirstResponder];
}
return YES;
}



Configuring a date formatter

- (void)viewDidLoad {
[super viewDidLoad];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setGeneratesCalendarDates:YES];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setCalendar:[NSCalendar autoupdatingCurrentCalendar]];
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
DOB.placeholder = [NSString stringWithFormat:@"Example: %@",[dateFormatterstringFromDate:[NSDate date]]];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{[textField resignFirstResponder];
if ([textField.text isEqualToString:@""])
return;

switch (textField.tag){
case DOBField:
NSDate *theDate = [dateFormatter dateFromString:textField.text];if (theDate)
[inputDate setObject:theDate forKey:MyAppPersonDOBKey];break;
default:
break;
}
}


UINavigationBar 设置背景图片
iPhone 开发中, 有时候我们想给导航条添加背景图片, 实现多样化的导航条效果,

其他方法往往无法达到理想的效果, 经过网上搜索及多次实验, 确定如下最佳实现方案:
UINavigatonBar 增加如下 Category(类别:提供一种为某个类添加方法而又不必编写子

类的途径,类别只能添加成员函数,不能添加数据成员):

@implementation UINavigationBar (CustomImage)- (void)drawRect:(CGRect)rect {

UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];

[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];}

@end

例如, 在我的项目中, 添加如下代码://///////////////////////////////////////////////////////
/* input: The image and a tag to later identify the view */@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {

UIImage *image = [UIImage imageNamed: @"title_bg.png"];

[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];}

@end
/////////////////////////////////////////////////////////
@implementation FriendsPageViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.- (void)viewDidLoad {

self.navigationBar.tintColor = [UIColor purpleColor];

[self initWithRootViewController:[[RegPageViewController alloc] init]];

[super viewDidLoad];}










你可能感兴趣的:(ios)