iOS小知识点(三)

来源:互联网 发布:如何开实体淘宝店 编辑:程序博客网 时间:2024/04/27 22:07
UITouch
手指的触摸范围:64X64 
 
#pragma mark -
#pragma mark Touch Events
 
- (void)touchesBegan:(NSSet *) toucheswithEvent:(UIEvent *) event{
originFrame = bookCover.frame;
NSLog(@"%s %d",__FUNCTION__,__LINE__);
 
if ([touches count] == 2) 
{
NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouchesobjectAtIndex:0];
UITouch *secondTouch =[twoTouchesobjectAtIndex:1];
CGPoint firstPoint =[firstTouchlocationInView:bookCover];
CGPoint secondPoint =[secondTouchlocationInView: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 *) toucheswithEvent:(UIEvent *) event{ 
 
if([touches count] == 2)

NSLog(@"%s %d",__FUNCTION__,__LINE__);
 
NSArray *twoTouches = [touches allObjects];
UITouch *firstTouch = [twoTouchesobjectAtIndex:0];
UITouch *secondTouch =[twoTouchesobjectAtIndex:1];
 
CGPoint firstPoint =[firstTouchlocationInView:bookCover];
CGPoint secondPoint =[secondTouchlocationInView: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 *) toucheswithEvent:(UIEvent *) event{
UITouch *touch = [touches anyObject];
 
UITouch双击图片变大/还原
if ([touch tapCount] == 2) 
{
NSLog(@"%s %d",__FUNCTION__,__LINE__);
 
if (!flag) {
[bookCoversetFrame: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 {
[bookCoversetFrame: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*)view
view window
 
Getting Touch Attributes
tapCount(read only) times*****p(read only)phase(readonly)
 
Getting a Touch Object's GestureRecognizers
gestureRecognizers 
 
Touch Phase
UITouchPhaseBegan
UITouchPhaseMoved
UITouchPhaseStationary
UITouchPhaseEnded
UITouchPhaseCancelled
 
Plist里读内容
NSString *plistPath = [[NSBundlemainBundle] pathForResource:@"book"ofType:@"plist"];
NSDictionary *dictionary = [[NSDictionaryalloc]initWithContentsOfFile:plistPath];
NSString *book =[dictionaryobjectForKey:bookTitle];
[textView setText:book];
 
(void) initialize {
NSUserDefaults = [NSUserDefaultsstandardUserDefaults];
NSDictionary *appDefaults =[NSDictionarydictionaryWithObject:@"YES"forKey:@"DeleteBackup"];
[defaults registerDefaults:appDefaults];
}
 
To get a value of a default, use thevalueForKey:method:
[[theDefaultsController values]valueForKey:@"userName"];
To set a value for a default, usesetValue:forKey:
[[theDefaultsController values]setValue:newUserNameforKey:@"userName"];
 
[[NSUserDefaults standardUserDefaults]setValue:aValeforKey:aKey];
[[NSUserDefaultsstandardUserDefaults]valueForKey:aKey];
 
获取Documents目录
NSArray *paths=NSSearchPathForDictionariesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES);
NSString *documentsDirectory =[pathsobjectAtIndex:0];
NSString *filename =[documentsDirectory 
stringByAppendingPathComponent:@"theFile.txt"];
 
获取tmp目录
NSString *tempPath =NSTemporaryDirectory();
NSString *tempFile =[tempPathstringByAppendingPathComponent:@"tempFile.txt"];
 
[[NSUserDefaults standardUserDefaults]setObject:dataforKey:@"someKey"];
[[NSUserDefaults standardUserDefaults]objectForKey:aKey];

自定义NavigationBar
navigationBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0,0, 320, 44)];
[navigationBarsetBarStyle:UIBarStyleBlackOpaque];
 
myNavigationItem = [[UINavigationItemalloc]initWithTitle:@"Setting"];
[navigationBarsetItems:[NSArrayarrayWithObject:myNavigationItem]];
[self.view addSubview:navigationBar];
 
backButton = [[UIBarButtonItem alloc]initWithTitle:@"Back"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(back)];
myNavigationItem.leftBarButtonItem =backButton;
 
 
利用Safari打开一个链接
NSURL *url =[NSURLURLWithString:@"http://www.cnblogs.com/tracy-e/"];
[[UIApplication sharedApplication]openURL:url];
 
利用UIWebView显示pdf文件、网页。。。
webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320,480)];
[webView setDelegate:self];
[webView setScalesPageToFit:YES];
[webViewsetAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
[webView setAllowsInlineMediaPlayback:YES];
[self.view addSubview:webView];
NSString *pdfPath = [[NSBundle mainBundle]pathForResource:@"ojc"ofType:@"pdf"]; 
NSURL *url =[NSURLfileURLWithPath:pdfPath]; 
NSURLRequest *request =[NSURLRequestrequestWithURL:url 
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5];
[webView loadRequest:request];
 
 
[myWebViewloadRequest:[NSURLRequestrequestWithURL:[NSURL 
                      URLWithString:@"http://www.cnblogs.com/tracy-e/"]]];
 
NSString *errorString =[NSStringstringWithFormat:@"<html><center><fontsize= 
+5 color ='red'>AnErrorOccurred:<br>%@</fone></center></html>",error];
[myWebView loadHTMLString:errorStringbaseURL:nil];
 
//Stopping a load request when the view istodisappear
- (void)viewWillDisappear:(BOOL)animate{
if ([myWebView loading]){
[myWebView stopLoading];
}
myWebView.delegate = nil;
[UIApplicati*****hareApplication].networkActivityIndicatorVisible =NO;
}

汉字转码
NSString *oriString =@"\u67aa\u738b";
NSString *escapedString =[oriString 
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 
 
Checking for background support on earlierversi***** ofiOS
UIDevice *device = [UIDevicecurrentDevice];
BOOL backgroundSupported = NO;
if([devicerespondsToSelector:@selector(isMultitaskingSupported)]){
backgroundSupported =device.multitaskingSupported;
}
 
Being aResp*****ible,Multitasking-AwareApplication 
# Do not make any OpenGL ES calls from yourcode.
# Cancel any Bonjour-related servicesbefore beingsuspended.
# Be prepared to handle connection failuresin your network-basedsockets.
# Save your application state before movingto thebackground.
# Release any unneeded memory when movingto thebackground.
# Stop using shared system resources beforebeingsuspended.
# Avoid updating your windows and views.
# Respond to connect and disconnectnotification for externalaccessories.
# Clean up resource for active alerts whenmoving to thebackground.
# Remove sensitive information from viewsbefore moving to thebackground.
# Do minimal work while running in thebackground.
 
Handing the Keyboard notificati*****
//Call this method somewhere in your viewcontroller setupcode
- (void) registerForKeyboardNotificati*****{
 
[[NSNotificationCenterdefaultCenter]addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification 
object:nil];
[[NSNotificationCenterdefaultCenter]addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification
object:nil];
 
}
 
//Called when theUIKeyboardDidShowNotification issent
- (void)keyboardWasShown:(NSNotification*)aNotification{
if(keyboardShown)
return;
NSDictionary *info = [aNotificationuserInfo];
 
//get the size of the keyboard. 
NSValue *aValue =[infoobjectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValueCGRectValue].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];
[scrollViewscrollRectToVisible:textFieldRectanimated:YES];
 
keyboardShown = YES; 
}
 
//Called when theUIKeyboardDidHideNotification issent
- (void)keyboardWasHidden:(NSNotification*)aNotification{
NSDictionary *info = [aNotificationuserInfo];
 
//Get the size of the keyboard.
NSValue *aValue =[infoobjectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValueCGRectValue].size;
 
//Reset the height of the scroll view toits originalvalue
CGRect 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 = [[selftableView]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:[NSLocalecurrentLocale]];
[dateFormattersetCalendar:[NSCalendarautoupdatingCurrentCalendar]];
[dateFormattersetTimeZone:[NSTimeZonedefaultTimeZone]];
[dateFormattersetDateStyle:NSDateFormatterShortStyle];
DOB.placeholder = [NSStringstringWithFormat:@"Example:%@",[dateFormatter stringFromDate:[NSDatedate]]];
}
 
-(void)textFieldDidEndEditing:(UITextField*)textField{
[textField resignFirstResponder];
if ([textField.textisEqualToString:@""])
return;
switch (textField.tag){
case DOBField:
NSDate *theDate =[dateFormatterdateFromString:textField.text];
if (theDate)
[inputDatesetObject:theDateforKey:MyAppPersonDOBKey];
break;
default:
break;
}
}
 
tableViewcell高度

tableViewcell高度除了在delegate中指定外,还可以在任意位置以[tableViewsetRowHeight:44]的方式指定
 
[[self navigationItem]setLeftBarButtonItem:[selfeditButtonItem]];
 
-(void)setEditing:(BOOL)editinganimated:(BOOL)animated{
[super setEditing:editing animated:animated];
if (editing){
...... 
}
else{
......

}
 
One added a subview to a view, release thesubview to avoid theextra retain count of it, Because when you insert a viewas asubview using addSubview:, the subview is retained by itssuperview. When youremove the subview from its superview using theremoveFromSuperview: method,subview isautoreleased.

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  
 
例如, 在我的项目中, 添加如下代码:
/////////////////////////////////////////////////////////  
  
@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 FriendsPageViewControlle 
// Implement viewDidLoad to do additional setup after loading the view, typically from nib.  
(void)viewDidLoad     
self.navigationBar.tintColor [UIColor purpleColor];  

[self initWithRootViewController:[[RegPageViewController alloc] init]];  
[super viewDidLoad];  
 
......  
原创粉丝点击