iOS-常用开发代码

1.打印继承关系 
po [self recursiveDescription]
<MySearchBar: 0x12c61c990; baseClass = UISearchBar; frame = (0 0; 320 44); text = ''; gestureRecognizers = <NSArray: 0x17405a700>; layer = <CALayer: 0x1740391e0>>
   | <UIView: 0x1741922e0; frame = (0 0; 320 44); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x1740392a0>>
   |    | <UISearchBarBackground: 0x12c61d450; frame = (0 0; 320 44); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x1740392e0>>
   |    | <UISearchBarTextField: 0x12c624880; frame = (0 0; 0 0); text = ''; clipsToBounds = YES; opaque = NO; gestureRecognizers = <NSArray: 0x17405e600>; layer = <CALayer: 0x17403bdc0>>
   |    |    | <_UISearchBarSearchFieldBackgroundView: 0x12c624c70; frame = (0 0; 0 0); opaque = NO; autoresize = W+H; userInteractionEnabled = NO; layer = <CALayer: 0x17403cba0>>

2.系统设置导航栏左滑退出
    // 设置系统左滑退出
   
self . navigationController . interactivePopGestureRecognizer . enabled = YES ;
    self.navigationController.interactivePopGestureRecognizer.delegate= self;
3.拉伸图片
UIEdgeInsets edge1= UIEdgeInsetsMake ( 10 , 10 , 10 , 10 );
   
UIImage *btnImage = [ UIImage imageNamed : @"anhaoFour_departmentBackground" ];
    btnImage = [btnImage
resizableImageWithCapInsets :edge1 resizingMode : 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. UIView autoresizingMask
  如果视图的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按钮执行的是换行功能,不能达到关闭键盘的目的。解决方法有两个:一个是通过捕捉touch End事件,当用户点击空白区域时关闭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 = [[
self alloc ] init ];
    });
   
return testModelSafe;
}
// 创建单例
+ (
id ) sharedTestModel
{
   
static XHTestModel *testModelShared = nil ;
   
if (testModelShared == nil ) {
        testModelShared = [[
XHTestModel alloc ] init ];
    }
   
return testModelShared;
}
15.自适应Label高度
- ( CGSize )getTextSize:( NSString *)text andFontSize:( CGFloat )fontSize andMaxSize:( CGSize )maxSize
{
   
// 设置文章段落风格
   
NSMutableParagraphStyle *paragraphStyle = [[ NSMutableParagraphStyle alloc ] init ];
    paragraphStyle.
lineBreakMode = NSLineBreakByWordWrapping ;
   
   
// 设置行间距
//    paragraphStyle.lineSpacing = 3.0f;
   
// 设置段间距
//    paragraphStyle.paragraphSpacing = 20.0f;
   
   
// 设置字体等属性 :NSKernAttributeName( 设置字间距 )- 该属性所对应的值是一个 NSNumber 对象 ( 整数 ) 。字母紧排指定了用于调整字距的像素点数。字母紧排的效果依赖于字体。值为 0 表示不使用字母紧排。默认值为 0
   
NSDictionary *attributes = @{ NSFontAttributeName :[ UIFont systemFontOfSize :fontSize], NSParagraphStyleAttributeName :paragraphStyle, NSKernAttributeName :[ NSNumber numberWithInt : 4 ] } ;
   
CGSize size = [text boundingRectWithSize :maxSize options : NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine attributes :attributes context : 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 <CoreText/CoreText.h>
     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. [[ NSNotificationCenter defaultCenter ] addObserver : self selector : @selector (dealKeyboadShow:) name : UIKeyboardWillShowNotification object : nil ];
   
// 键盘隐藏的事件通知
    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(dealKeyboadHide:)name:UIKeyboardWillHideNotificationobject:nil];

// 键盘显示事件通知的处理方法
-(
void )dealKeyboadShow:( NSNotification *)noti
{
   
NSLog ( @"dealKeyboadShow" );
   
    [
UIView beginAnimations : @"" context : nil ];
    [
UIView setAnimationDuration : 0.5 ];
   
   
// 处理键盘的遮挡
   
loginButton . frame = CGRectMake ( 100 , 210 , 80 , 30 );
   
registerButton . frame = CGRectMake ( 190 , 210 , 80 , 30 );
   
    [
UIView commitAnimations ];
}

-(
void )dealKeyboadHide:( NSNotification *)noti
{
   
NSLog ( @"dealKeyboadShow" );
   
    [
UIView beginAnimations : @"" context : nil ];
    [
UIView setAnimationDuration : 0.5 ];
   
   
// 处理键盘的遮挡
   
loginButton . frame = CGRectMake ( 100 , 400 , 80 , 30 );
   
registerButton . frame = CGRectMake ( 190 , 400 , 80 , 30 );
   
    [
UIView commitAnimations ];
}



2.block形式

// UIKeyboardWillShowNotification 键盘即将显示 Block 形式
    [[ NSNotificationCenter defaultCenter ] addObserverForName : UIKeyboardWillShowNotification object : nil queue :[ NSOperationQueue mainQueue ] 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 ];
       
        [
UIView animateWithDuration :[duration doubleValue ] animations :^{
            [
UIView setAnimationBeginsFromCurrentState : YES ];
            [
UIView setAnimationCurve :[curve intValue ]];
           
// 处理键盘的遮挡
           
loginButton . frame = CGRectMake ( 100 , 500 -keyBoardSize. height , 80 , 30 );
           
registerButton . frame = CGRectMake ( 190 , 500 -keyBoardSize. height , 80 , 30 );
        }
completion :^( BOOL finished) {
           
        }];

    }];
   
    [[
NSNotificationCenter defaultCenter ] addObserverForName : UIKeyboardWillHideNotification object : nil queue :[ NSOperationQueue mainQueue ] 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 ];
       
        [
UIView animateWithDuration :[duration doubleValue ] animations :^{
            [
UIView setAnimationBeginsFromCurrentState : YES ];
            [
UIView setAnimationCurve :[curve intValue ]];
           
// 处理键盘的遮挡
           
loginButton . frame = CGRectMake ( 100 , 500 , 80 , 30 );
           
registerButton . frame = CGRectMake ( 190 , 500 , 80 , 30 );
        }
completion :^( BOOL finished) {
           
        }];


    }];

3.block通知
// 通知   当得到消息的时候 把页面返回   返回的页面完成后才可以支持跳转
    [[
NSNotificationCenter defaultCenter ] addObserverForName : @"DismissDuihuaViewController" object : nil queue :[ NSOperationQueue mainQueue ] usingBlock :^( NSNotification *note) {
        [
self dismissViewControllerAnimated : YES completion :^{
           
//            [self performSelector:@selector(presentDuihuaView) withObject:nil afterDelay:0.5];
           
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"presentDuihuaView" object:nil];
        }];
        [
self . navigationController popViewControllerAnimated : YES ];
        [
self performSelector : @selector (presentDuihuaView) withObject : nil afterDelay : 0.5 ];
    }];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值