iOS小知識點(三)

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(read only)
 
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 = [NSUserDefaults standardUserDefaults];
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:newUserName forKey:@"userName"];
 
[[NSUserDefaults standardUserDefaults]setValue:aVale forKey:aKey];
[[NSUserDefaults standardUserDefaults]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:data forKey:@"someKey"];
[[NSUserDefaults standardUserDefaults] objectForKey:aKey];

自定義NavigationBar
navigationBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[navigationBarsetBarStyle:UIBarStyleBlackOpaque];
 
myNavigationItem = [[UINavigationItemalloc] initWithTitle:@"Setting"];
[navigationBar setItems:[NSArrayarrayWithObject:myNavigationItem]];
[self.view addSubview:navigationBar];
 
backButton = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStylePlain target: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];
 
 
[myWebView loadRequest:[NSURLRequestrequestWithURL:[NSURL 
                       URLWithString:@"http://www.cnblogs.com/tracy-e/"]]];
 
NSString *errorString = [NSStringstringWithFormat:@"<html><center><font size= 
+5 color ='red'>An ErrorOccurred:<br>%@</fone></center></html>",error];
[myWebView loadHTMLString:errorStringbaseURL:nil];
 
//Stopping a load request when the view isto disappear
- (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***** of iOS
UIDevice *device = [UIDevicecurrentDevice];
BOOL backgroundSupported = NO;
if ([devicerespondsToSelector:@selector(isMultitaskingSupported)]){
backgroundSupported =device.multitaskingSupported;
}
 
Being a Resp*****ible,Multitasking-AwareApplication 
# Do not make any OpenGL ES calls from yourcode.
# Cancel any Bonjour-related servicesbefore being suspended.
# Be prepared to handle connection failuresin your network-based sockets.
# Save your application state before movingto the background.
# Release any unneeded memory when movingto the background.
# Stop using shared system resources beforebeing suspended.
# Avoid updating your windows and views.
# Respond to connect and disconnectnotification for external accessories.
# Clean up resource for active alerts whenmoving to the background.
# Remove sensitive information from viewsbefore moving to the background.
# Do minimal work while running in thebackground.
 
Handing the Keyboard notificati*****
//Call this method somewhere in your viewcontroller setup code
- (void) registerForKeyboardNotificati*****{
 
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification 
object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification
object:nil];
 
}
 
//Called when theUIKeyboardDidShowNotification is sent
- (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:textFieldRect animated:YES];
 
keyboardShown = YES; 
}
 
//Called when theUIKeyboardDidHideNotification is sent
- (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 original value
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 = [[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:[NSLocalecurrentLocale]];
[dateFormatter setCalendar:[NSCalendarautoupdatingCurrentCalendar]];
[dateFormatter setTimeZone:[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)
[inputDate setObject:theDateforKey:MyAppPersonDOBKey];
break;
default:
break;
}
}
 
tableViewcell高度

tableViewcell高度除了在delegate中指定外,還可以在任意位置以[tableView setRowHeight:44]的方式指定
 
[[self navigationItem]setLeftBarButtonItem:[self editButtonItem]];
 
- (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 the extra retain count of it, Because when you insert a viewas a subview using addSubview:, the subview is retained by its superview. When youremove the subview from its superview using the removeFromSuperview: method,subview is autoreleased.

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 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];  
}  
......  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章