iOS小知识点总结

  • 1.计算有多少组通用公式
    示例:服务器返回15个数据,每组8个
// 15 / 8 = 1
// 15 % 8 > 0  = 1(真)
  _pageC.numberOfPages = _mainVM.rowNumber / 8 + (_mainVM.rowNumber % 8  >  0);
  • 计算总共多少行通用公式
NSUInteger count = squares.count;
int totalCols = 4;
unsigned long totalRows = (count + totalCols - 1) / 4;
  • 2.自己写的宏定义要用小k开头,以区分系统级别的宏
#define kShowWarningDelayDuration   1
#define kTimeoutDuration 30
  • 3.block 三目运算判断block是否为nil
!block ?: block();
  • 4.如何手动调用UICollectionView/tableView的选中cell方法
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
  • 5.查找最后一个逗号,并删除
NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
 if (range.location != NSNotFound)
[string deleteCharactersInRange:range];
// 或者:
NSString *cccc = [cut substringToIndex:[cut length] - 1];
  • 6.window的Rect
// 在iOS7以上,所有控制器默认都是全屏的,上面20的状态栏高度也属于控制器
//返回的是带有状态栏的Rect
CGrect screenBounds = [ [UIScreen mainScreen] bounds]; 
//不包含状态栏的Rect 
CGRect viewBounds = [ [UIScreen mainScreen] applicationFrame];
  • 7.用于去掉cell的分割线左侧15的空隙
  - (void)awakeFromNib {
    self.separatorInset = UIEdgeInsetsZero;
    self.layoutMargins = UIEdgeInsetsZero;
    self.preservesSuperviewLayoutMargins = NO;
}
  • 8.富文本属性(修改字符串中指定文字的颜色,字体大小)
  //红色¥ + 黑色数字
  NSDictionary *str1Dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15], NSForegroundColorAttributeName: [UIColor redColor]};
  NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:@"¥" attributes:str1Dic];
    
  NSDictionary *str2Dic = @{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName: [UIColor blackColor]};
  NSAttributedString *str2 = [[NSAttributedString alloc] initWithString:price attributes:str2Dic];
  NSMutableAttributedString *attr = [NSMutableAttributedString new];
  [attr appendAttributedString:str1];
  [attr appendAttributedString:str2];
  _priceLb.attributedText = attr;
  • 9.截取路径最后的部分,非常智能的方法
[self lastPathComponent];```
![Snip1.png](http://upload-images.jianshu.io/upload_images/987457-b9aba6390a07992d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 10.过滤
```objc
// break是结束整个循环体,continue是结束单次循环
// 过滤掉非UITabBarButton
if (![@"UITabBarButton" isEqualToString:NSStringFromClass(subview.class)]) continue;
if (subview.class != NSClassFromString(@"UITabBarButton")) continue;
  • 11.按钮选中状态更改三部曲
// 让上一个按钮取消选中状态
self.preBtn.selected = NO;
// 让当前按钮成为选中状态
btn.selected = YES;
// 让当前按钮变成上一个按钮
self.preBtn = btn;
  • 12.nil,NULL,NSNull区别
1、nil:一般赋值给空对象;
2、NULL:一般赋值给nil之外的其他空值。 NULL是C的,空地址,地址的数值是0,是个长整数;如SEL等;
  举个栗子(好重啊~):
[NSApp beginSheet:sheet modalForWindow:mainWindow
                modalDelegate:nil //pointing to an object
                didEndSelector:NULL //pointing to a non object/class
                contextInfo:NULL]; //pointing to a non object/class
3、NSNULL:NSNull只有一个方法:+ (NSNull *) null;
  [NSNull null]用来在NSArray和NSDictionary中加入非nil(表示列表结束)的空值.
4、当向nil发送消息时,返回NO,不会有异常,程序将继续执行下去;
  而向NSNull的对象发送消息时会收到异常。
  • 13.当一个控件添加自己的约束时候,必须设置系统的autorezing为NO;
self.btn.translatesAutoresizingMaskIntoConstraints = NO;
  • 14.SDWebImage 有两个宏 来判断程序在主线程运行
  // 需要导入#import "EMSDWebImageCompat.h"
  #define dispatch_main_sync_safe(block)\
    if ([NSThread isMainThread]) {\
        block();\
    } else {\
        dispatch_sync(dispatch_get_main_queue(), block);\
    }

  #define dispatch_main_async_safe(block)\
    if ([NSThread isMainThread]) {\
        block();\
    } else {\
        dispatch_async(dispatch_get_main_queue(), block);\
    }

  // 使用:
  dispatch_main_async_safe((^{
                self.headIcon.image = [UIImage imagenamed:fsf];
            }));
  • 15.UIApplicationUserDidTakeScreenshotNotification通知,当用户截屏时触发
    UIApplicationDidBecomeActiveNotification 通知 ,程序从后台进入前台的
    应用场景示例:扫描二维码的动画进入后台后会执行completion 的block,可以利用这个通知再次调用开始动画

  • 16.手机振动

  - (void)vibrate   {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
  • 17.一个View中三个按钮,获取点击按钮的索引,—>监听点击的是哪个按钮
NSUInteger index = [button.superview.subViews indexOfObject:button];

示例如下图

Snip20160522_7.png

  • 18.IBOutletCollection(ClassName)使用这个伪关键字,可以将界面上一组相同的控件连接到同一个数组中
    伪关键字的定义,可以从UIKit.framework的头文件UINibDeclarations.h找到如下定义:
#ifndef IBOutletCollection
#define IBOutletCollection(ClassName)
#endif

在Clang源码中,有更安全的定义方式,如下所示:

#define IBOutletCollection(ClassName) __attribute__((iboutletcollection(ClassName)))
  • 不过在使用IBOutletCollection时,需要注意两点:
  1. IBOutletCollection集合中对象的顺序是不确定的。我们通过调试方法可以看到集合中对象的顺序跟我们连接的顺序是一样的。但是这个顺序可能会因为不同版本的Xcode而有所不同。所以我们不应该试图在代码中去假定这种顺序。
  2. 不管IBOutletCollection(ClassName)中的控件是什么,属性的类型始终是NSArray。实际上,我们可以声明是任何类型,如NSSet,NSMutableArray,甚至可以是UIColor,但不管我们在此设置的是什么类,IBOutletCollection属性总是指向一个NSArray数组。
Snip20160522_9.png

  • 19.去掉BackBarButtonItem的文字
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
  • 20.去掉UITableView风格为group时候的最顶部的空白距离
    CGFLOAT_MIN 这个宏表示 CGFloat 能代表的最接近 0 的浮点数,,64 位下大概是 0.00(300左右个)0225 这个样子
    这样写单纯的为了避免一个魔法数字,这里用 0.1 效果是一样的
  CGRect frame=CGRectMake(0, 0, 0, CGFLOAT_MIN);
  self.tableView.tableHeaderView=[[UIView alloc]initWithFrame:frame];
  // 或
  - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) return CGFLOAT_MIN;
    return 6;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容