你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS-常用開發代碼

iOS-常用開發代碼

編輯:IOS開發綜合
1.打印繼承關系
po [self recursiveDescription]
; layer = >
| >
| | >
| | ; layer = >
| | | <_UISearchBarSearchFieldBackgroundView: 0x12c624c70; frame = (0 0; 0 0); opaque = NO; autoresize = W+H; userInteractionEnabled = NO; layer = >

2.系統設置導航欄左滑退出
// 設置系統左滑退出
self.navigationController.interactivePopGestureRecognizer.enabled= YES;
self.navigationController.interactivePopGestureRecognizer.delegate= self;
3.拉伸圖片
UIEdgeInsetsedge1=UIEdgeInsetsMake(10,10,10,10);
UIImage *btnImage = [UIImageimageNamed:@"anhaoFour_departmentBackground"];
btnImage = [btnImage resizableImageWithCapInsets:edge1resizingMode:UIImageResizingModeTile];
[nearPeerCell.departmentBtnsetBackgroundImage:btnImageforState:UIControlStateNormal];
4.NS_ENUM

5.屏幕尺寸
iphone4,4s === 3.5寸 === 960X640
iphone5,5s === 4.0寸=== 1136X640
iphone6 === 4.7寸 === 1334X750
iphone6+ === 5.5寸 === 2208X1242

ipad1 === 9.7寸=== 1024X768
ipad2 === 9.7寸=== 1024X768
The New iPad(Retina)=== 9.7寸=== 2048X1536
ipad4 === 9.7寸===2048X1536

ipad mini1 === 7.9寸=== 1024X768
ipad mini2 === 7.9寸===2048X1536
ipad mini2 === 7.9寸===2048X1536

6.UIViewautoresizingMask
  如果視圖的autoresizesSubviews屬性聲明被設置為YES,則其子視圖會根據autoresizingMask屬性的值自動進行尺寸調整。簡單配置一下視圖的自動尺寸調整掩碼常常就能使應用程序得到合適的行為;否則,應用程序就必須通過重載layoutSubviews方法來提供自己的實現。
  self.autoresizingMask=UIViewAutoresizingFlexibleWidth;//這個常量如果被設置,視圖的寬度將和父視圖的寬度一起成比例變化。否則,視圖的寬度將保持不變。
  
UIViewAutoresizingNone
這個常量如果被設置,視圖將不進行自動尺寸調整。
UIViewAutoresizingFlexibleHeight
這個常量如果被設置,視圖的高度將和父視圖的高度一起成比例變化。否則,視圖的高度將保持不變。
UIViewAutoresizingFlexibleWidth
這個常量如果被設置,視圖的寬度將和父視圖的寬度一起成比例變化。否則,視圖的寬度將保持不變。
UIViewAutoresizingFlexibleLeftMargin
這個常量如果被設置,視圖的左邊界將隨著父視圖寬度的變化而按比例進行調整。否則,視圖和其父視圖的左邊界的相對位置將保持不變。
UIViewAutoresizingFlexibleRightMargin
這個常量如果被設置,視圖的右邊界將隨著父視圖寬度的變化而按比例進行調整。否則,視圖和其父視圖的右邊界的相對位置將保持不變。
UIViewAutoresizingFlexibleBottomMargin
這個常量如果被設置,視圖的底邊界將隨著父視圖高度的變化而按比例進行調整。否則,視圖和其父視圖的底邊界的相對位置將保持不變。
UIViewAutoresizingFlexibleTopMargin
這個常量如果被設置,視圖的上邊界將隨著父視圖高度的變化而按比例進行調整。否則,視圖和其父視圖的上邊界的相對位置將保持不變。

7.NSArray NSDictionary

NSArray *array = @[@"你",@"我",@"他"];
NSLog(@"array[0] = %@",array[0]);//array[0] = 你

NSDictionary *dict = @{@"platform":@"ios",@"version":@"1.2"};
NSLog(@"dict[0] = %@",dict[@"platform"]);//dict[0] = ios


8.UITextView如何關閉鍵盤
UITextField可以響應鍵盤上的完成按鈕,關閉鍵盤,而UITextView不一樣,它的return按鈕或者Done按鈕執行的是換行功能,不能達到關閉鍵盤的目的。解決方法有兩個:一個是通過捕捉touchEnd事件,當用戶點擊空白區域時關閉UITextView打開的鍵盤;一個是增加一個帶有完成按鈕的UIToolbar(這個UIToolbar當鍵盤彈出的時候總是顯示在鍵盤的上方,很完美的貼在一起,鍵盤收起,它也會隨著收起)。當然,將這兩個方法都集成進來運用也是可以的。

下面提供第二種方法的詳細代碼:
UIToolbar * topView = [[UIToolbar alloc]
initWithFrame:CGRectMake(0, 0, 320, 30)];
[topView
setBarStyle:UIBarStyleDefault];

UIBarButtonItem * btnSpace =
[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self
action:nil];
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]
initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self
action:@selector(dismissKeyBoard)];
NSArray * buttonsArray = [NSArray
arrayWithObjects:btnSpace, doneButton, nil];
[btnSpace release];
[doneButton release];
[topView setItems:buttonsArray];

[m_myUITextView setInputAccessoryView:topView];

注:1.dismissKeyBoard是自定義的收起鍵盤的方法,可自定義其中的內容,比如執行[m_myUITextView
resignFirstResponder];
2.最後一行代碼setInputAccessoryView函數的調用是很關鍵的一句。

9.改變系統導航欄顏色字體

self.navigationController.navigationBarHidden = NO;
self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: [UIColor whiteColor],
UITextAttributeFont : [UIFont boldSystemFontOfSize:18]};

10.改變索引條背景和字體顏色
self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
self.tableView.sectionIndexColor = GRAY_BLUE_COLOR;

11.獲取tableview最頂部和最底部的cell
// self.meAnswerTableView.visibleCells當前可見的cell數組,該數組中得第一個cell就是頂部的headerCell,該數組中得最後一個cell就是頂部的footerCell
NSLog(@"%d",self.meAnswerTableView.visibleCells.count);
LCMeAnswerTableViewCell *cell = [self.meAnswerTableView.visibleCells objectAtIndex:0];
// 獲取頂部cell的index值
if (cell != nil) {
NSIndexPath *heaerIndex = [self.meAnswerTableView indexPathForCell:cell];
NSLog(@"heaerindex.row = %d,heaerindex.section = %d",heaerIndex.row,heaerIndex.section);
}

LCMeAnswerTableViewCell *lastcell = [self.meAnswerTableView.visibleCells objectAtIndex:self.meAnswerTableView.visibleCells.count-1];
if (lastcell != nil) {
NSIndexPath *footerIndext = [self.meAnswerTableView indexPathForCell:lastcell];
NSLog(@"footerIndext.row = %d,footerIndext.section = %d",footerIndext.row,footerIndext.section);
}
12.設置tableview分割線

首先在viewDidLoad方法中加上如下代碼:

if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {

[self.tableView setSeparatorInset:UIEdgeInsetsZero];

}

if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {

[self.tableView setLayoutMargins:UIEdgeInsetsZero];

}

然後在willDisplayCell方法中加入如下代碼:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {

[cell setSeparatorInset:UIEdgeInsetsZero];

}

if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {

[cell setLayoutMargins:UIEdgeInsetsZero];

}

}
xib設置如下




13.圖片緩存
//清理圖片緩存在viewdidload或者appdelegate或者自己需要的地方調用
[[SDImageCache sharedImageCache] clearDisk];
[[SDImageCache sharedImageCache] clearMemory];
在tableview的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中調用
// 從磁盤緩存中獲取緩存圖片,如果圖片存在則直接調用,如果沒有則下載。SDWebImageProgressiveDownload下載優先
UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:avatar];
if (image) {
photo.image = image;
} else {
[photo setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"noavatar_big"]options:SDWebImageProgressiveDownload];
}
14.創建單例(線程安全)
//創建單例(線程安全)
+ (id) sharedTestModelSafe
{
static XHTestModel *testModelSafe = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
testModelSafe = [[selfalloc]init];
});
return testModelSafe;
}
//創建單例
+ (id) sharedTestModel
{
static XHTestModel *testModelShared = nil;
if (testModelShared ==nil) {
testModelShared = [[XHTestModelalloc]init];
}
return testModelShared;
}
15.自適應Label高度
- (CGSize)getTextSize:(NSString*)text andFontSize:(CGFloat)fontSize andMaxSize:(CGSize)maxSize
{
// 設置文章段落風格
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc]init];
paragraphStyle.lineBreakMode= NSLineBreakByWordWrapping;

// 設置行間距
// paragraphStyle.lineSpacing = 3.0f;
// 設置段間距
// paragraphStyle.paragraphSpacing = 20.0f;

// 設置字體等屬性:NSKernAttributeName(設置字間距)-該屬性所對應的值是一個NSNumber 對象(整數)。字母緊排指定了用於調整字距的像素點數。字母緊排的效果依賴於字體。值為0 表示不使用字母緊排。默認值為0
NSDictionary *attributes = @{NSFontAttributeName:[UIFontsystemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:[NSNumbernumberWithInt:4]};
CGSize size = [text boundingRectWithSize:maxSizeoptions:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLineattributes:attributescontext:nil].size;

paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
// ceil返回大於或者等於指定表達式的最小整數
size.height= ceil(size.height);
size.width= ceil(size.width);
return size;
/*
注意如果這裡設置了字間距,行間距和段間距,那麼相應的label等控件也需要進行設置:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, kScreenWidth-20, height)];
label.text = text;
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:14];
label.textAlignment = NSTextAlignmentLeft;

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
// 行間距
paragraphStyle.lineSpacing = 3.0f;
// 段間距
paragraphStyle.paragraphSpacing = 20.0f;

// 設置字體等屬性
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSParagraphStyleAttributeName:paragraphStyle};
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
// 設置字間距

long number = 0;
// #import 
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, &number);
[attr addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0, [attr length])];
CFRelease(num);

#if 0
或者:
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:[NSNumber numberWithInt:4]};
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];

#endif

label.attributedText = attr;
*/
}
16.鍵盤隱藏/顯示+動態計算鍵盤高度+block通知
1. [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(dealKeyboadShow:)name:UIKeyboardWillShowNotificationobject:nil];
//鍵盤隱藏的事件通知
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(dealKeyboadHide:)name:UIKeyboardWillHideNotificationobject:nil];

//鍵盤顯示事件通知的處理方法
-(void)dealKeyboadShow:(NSNotification*)noti
{
NSLog(@"dealKeyboadShow");

[UIViewbeginAnimations:@""context:nil];
[UIViewsetAnimationDuration:0.5];

//處理鍵盤的遮擋
loginButton.frame= CGRectMake(100,210,80,30);
registerButton.frame= CGRectMake(190,210,80,30);

[UIViewcommitAnimations];
}

-(void)dealKeyboadHide:(NSNotification*)noti
{
NSLog(@"dealKeyboadShow");

[UIViewbeginAnimations:@""context:nil];
[UIViewsetAnimationDuration:0.5];

//處理鍵盤的遮擋
loginButton.frame= CGRectMake(100,400,80,30);
registerButton.frame= CGRectMake(190,400,80,30);

[UIViewcommitAnimations];
}



2.block形式

// UIKeyboardWillShowNotification鍵盤即將顯示Block形式
[[NSNotificationCenterdefaultCenter]addObserverForName:UIKeyboardWillShowNotificationobject:nilqueue:[NSOperationQueuemainQueue]usingBlock:^(NSNotification*note) {
// 添加移動動畫,使視圖跟隨鍵盤移動
// 將通知中的信息轉化成字典
NSDictionary *infomation = [note userInfo];
// 獲取鍵盤展示結束之後的尺寸
NSValue *value = [infomation objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyBoardSize = [value CGRectValue].size;
// 鍵盤動畫曲線
NSNumber *curve = [infomation objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// 鍵盤的動畫時間
NSNumber *duration = [infomation objectForKey:UIKeyboardAnimationDurationUserInfoKey];

[UIViewanimateWithDuration:[durationdoubleValue]animations:^{
[UIViewsetAnimationBeginsFromCurrentState:YES];
[UIViewsetAnimationCurve:[curveintValue]];
//處理鍵盤的遮擋
loginButton.frame= CGRectMake(100,500-keyBoardSize.height,80,30);
registerButton.frame= CGRectMake(190,500-keyBoardSize.height,80,30);
} completion:^(BOOLfinished) {

}];

}];

[[NSNotificationCenterdefaultCenter]addObserverForName:UIKeyboardWillHideNotificationobject:nilqueue:[NSOperationQueuemainQueue]usingBlock:^(NSNotification*note) {
// 添加移動動畫,使視圖跟隨鍵盤移動
// 將通知中的信息轉化成字典
NSDictionary *infomation = [note userInfo];
// 獲取鍵盤展示結束之後的尺寸
NSValue *value = [infomation objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyBoardSize = [value CGRectValue].size;
// 鍵盤動畫曲線
NSNumber *curve = [infomation objectForKey:UIKeyboardAnimationCurveUserInfoKey];
// 鍵盤的動畫時間
NSNumber *duration = [infomation objectForKey:UIKeyboardAnimationDurationUserInfoKey];

[UIViewanimateWithDuration:[durationdoubleValue]animations:^{
[UIViewsetAnimationBeginsFromCurrentState:YES];
[UIViewsetAnimationCurve:[curveintValue]];
//處理鍵盤的遮擋
loginButton.frame= CGRectMake(100,500,80,30);
registerButton.frame= CGRectMake(190,500,80,30);
} completion:^(BOOLfinished) {

}];


}];

3.block通知
//通知當得到消息的時候 把頁面返回返回的頁面完成後才可以支持跳轉
[[NSNotificationCenterdefaultCenter]addObserverForName:@"DismissDuihuaViewController"object:nilqueue:[NSOperationQueuemainQueue]usingBlock:^(NSNotification*note) {
[selfdismissViewControllerAnimated:YEScompletion:^{
// [self performSelector:@selector(presentDuihuaView) withObject:nil afterDelay:0.5];
// [[NSNotificationCenter defaultCenter] postNotificationName:@"presentDuihuaView" object:nil];
}];
[self.navigationControllerpopViewControllerAnimated:YES];
[selfperformSelector:@selector(presentDuihuaView)withObject:nilafterDelay:0.5];
}];

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved