iOS 总结
2016-08-27 本文已影响882人
小傑
1,打印View所有子视图
po [[self view]recursiveDescription]
2.阿拉伯数字转汉字(1转一)
原值:2.7999999999
typedef CF_ENUM(CFIndex, CFNumberFormatterRoundingMode) {
kCFNumberFormatterRoundCeiling = 0,//四舍五入,直接输出3
kCFNumberFormatterRoundFloor = 1,//保留小数输出2.8
kCFNumberFormatterRoundDown = 2,//加上了人民币标志,原值输出¥2.8
kCFNumberFormatterRoundUp = 3,//本身数值乘以100后用百分号表示,输出280%
kCFNumberFormatterRoundHalfEven = 4,//输出2.799999999E0
kCFNumberFormatterRoundHalfDown = 5,//原值的中文表示,输出二点七九九九。。。。
kCFNumberFormatterRoundHalfUp = 6//原值中文表示,输出第三
};
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = kCFNumberFormatterRoundHalfDown;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:12]];
NSLog(@"str = %@", string);
//阿拉伯数字转中文格式
+(NSString *)translation:(NSString *)arebic
{
NSString *str = arebic;
NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
NSMutableArray *sums = [NSMutableArray array];
for (int i = 0; i < str.length; i ++) {
NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
NSString *a = [dictionary objectForKey:substr];
NSString *b = digits[str.length -i-1];
NSString *sum = [a stringByAppendingString:b];
if ([a isEqualToString:chinese_numerals[9]])
{
if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
{
sum = b;
if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
{
[sums removeLastObject];
}
}else
{
sum = chinese_numerals[9];
}
if ([[sums lastObject] isEqualToString:sum])
{
continue;
}
}
[sums addObject:sum];
}
NSString *sumStr = [sums componentsJoinedByString:@""];
NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
NSLog(@"%@",str);
NSLog(@"%@",chinese);
return chinese;
}
3.app内启动用户评价
//app内启动用户评价
NSString *url = [NSString stringWithFormat:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d",490062954];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
490062954是程序的Apple ID,可以在iTunes Connect中查到。
比如在用户使用一段时间后,弹出一个对话框提醒用户去评价:
NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"去给'%@'打分吧!",appName]
message:@"您的评价对我们很重要"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"稍后评价",@"去评价",nil];
[alertView show];
软件版本: NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
//iOS跳转到App Store下载应用评分
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
4.字典->模型 模型->字典
//这是使用系统的方法 descriptionDe 代替 description(不使用MJ)
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
if ([key isEqualToString:@"description"]) {
self.descriptionDe = value;
}
}
1. JSON -> Model【最简单的字典转模型】
// JSON -> User
User *user = [User mj_objectWithKeyValues:dict];
2.JSONString -> Model【JSON字符串转模型】
// 1.Define a JSONString
NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20}";
// 2.JSONString -> User
User *user = [User mj_objectWithKeyValues:jsonString];
3.模型中的属性名和字典中的key不相同(用ID代替id,后面类似)
[Student mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{
@"ID" : @"id",
@"desc" : @"desciption",
@"oldName" : @"name.oldName",
@"nowName" : @"name.newName",
@"nameChangedTime" : @"name.info[1].nameChangedTime",
@"bag" : @"other.bag"
};
}];
4.JSON array -> model array【将一个字典数组转成模型数组】
NSArray *userArray = [User mj_objectArrayWithKeyValuesArray:dictArray];
#pragma mark -模型->字典
5.Model -> JSON【将一个模型转成字典】
Status *status = [[Status alloc] init];
NSDictionary *statusDict = status.mj_keyValues;
6. Model array -> JSON array【将一个模型数组转成字典数组】
NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
7.转化为JSONNString
[dict mj_JSONNString]
5.关于push,pop,model,dimiss
遍历popToViewController跳转的控制器,然后跳到指定位置
for (int i = 0; i<self.navigationController.viewControllers.count; i++) {
UIViewController * controller = self.navigationController.viewControllers[i];
if ([controller isKindOfClass:InformMainViewController.class]) {
InformMainViewController * vc = (InformMainViewController *)controller;
[self.navigationController popToViewController:vc animated:YES];
break;
}
}
pop回指定控制器
1. NSArray *viewControllers=[self.navigationController viewControllers];
2. UIViewController *controller=[viewControllers objectAtIndex:1];
3. [self.navigationController popToViewController:controller animated:YES];
3.关于push,pop,model,dimiss
1.注意�:如果用stroyboard的话,要拉线,不然可能会出现不了界面!!!
[self performSegueWithIdentifier:@"MyApply-To-FlowDetail" sender:nil];
//跳转前传值
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"MyApply-To-FlowDetail"]) {
FlowDetailController * controller = segue.destinationViewController;
if (_bool_fromApply) {
controller.flow_id = _flow_id;
}
else
{
controller.flow_id = _flowInfoModel.id;
}
controller.delegate = self;
}
}
2.第二种方法
UIStoryboard *story = [UIStoryboard storyboardWithName:@"My" bundle:nil];
MyEnterCompanyNameController *vc = (MyEnterCompanyNameController *)[story instantiateViewControllerWithIdentifier:@"MyEnterCompanyName"];
[self.navigationController pushViewController:vc animated:YES];
4.设置转场动画modalTransitionStyle
1.系统的
UIViewController *detailViewController = [[UIViewController alloc] init];
detailViewController.modalTransitionStyle = UIModalTransitionStylePartialCurl; // 设置动画效果
[self presentModalViewController:detailViewController animated:YES];
2.自定义的
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"My" bundle:nil];
MyJoinCompanyController *vc = (MyJoinCompanyController *)[storyboard instantiateViewControllerWithIdentifier:@"MyJoinCompanyController"];
CATransition *animation = [CATransition animation];
[animation setDuration:0.5];
[animation setType:kCATransitionPush];
[animation setSubtype:kCATransitionFromRight];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[[vc.view layer] addAnimation:animation forKey:@"pushToView"];
[self presentViewController:vc animated:YES completion:nil];
5.如果底部有tabbar的话,push要加上
vc.hidesBottomBarWhenPushed = YES;
6.如果拖拽手势返回的时候,右上角有黑色,加这句
self.na
6.关于通知,delegate
1.delegate执行回调pop时,如果跨界面跳需要用NSNotificationCenter通知,(代理只能执行跳一个界面!!!!!),
第2种方法是目标控制器.h中声明一种方法来调用
7.判断app程序第一次启动方法
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
NSLog(@"第一次启动");
}else{
NSLog(@"不是第一次启动");
}
8.透明度
1.如果UIView B为半透明, 如何让加载上边的UIView C不透明?
设置ViewB的半透明时使用B.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8]
2. 有透明度的颜色
[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.2];
[UIColor colorWithWhite:1.0 alpha:0.2];
[[UIColor whiteColor] colorWithAlphaComponent:0.2];
9.用这方法可以遮住导航栏
[[UIApplication sharedApplication].keyWindow addSubview:self.view_shadow];
10.关于NSLog
1.点输出NSLog(@"point = %@",NSStringFromCGPoint(self.tableView.contentOffset));
11.NULL、nil、Nil这三者对于Objective-C中值是一样的,都是(void *)0,那么为什么要区分呢?又与NSNull之间有什么区别:
NULL是宏,是对于C语言指针而使用的,表示空指针
nil是宏,是对于Objective-C中的对象而使用的,表示对象为空
Nil是宏,是对于Objective-C中的类而使用的,表示类指向空
NSNull是类类型,是用于表示空的占位对象,与JS或者服务端的null类似的含意
12.NSDate的比较
NSDate *now = [[NSDate alloc] init];
if ([self.btn_date.date compare:now] == NSOrderedDescending) { // 前面的大于后面的
}
BOOL result = [a compare:b];
if (result == NSOrderedSame) { // NSOrderedSame = 0 完全一样
NSLog(@"a = b");
}else if(result == NSOrderedAscending) // NSOrderedAscending = -1
NSLog(@"a < b");
else{ //NSOrderedDescending = +1
NSLog(@"a > b");
}
13.关于Masonry
1.更新可以用update 或者 remake(移除之前的所有约束,然后添加新约束的方法是:mas_remakeConstraints。)
2.对于cell中需要添加删除变化cell位置的要用mas_remakeConstraints来设置约束,(因为它是添加约束与更新约束,不用会有问题!)
3.设置多行labl!
-(void)mostLineLabel
{
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:17];
label.text = @"Masonry是一个轻量级的布局框架与更好的包装AutoLayout语法。Masonry是一个轻量级的布局框架与更好的包装AutoLayout语法。asasadadadada";
label.textColor = [UIColor blackColor];
[self.view addSubview:label];
label.numberOfLines = 0;
//注意:这2句很重要
label.preferredMaxLayoutWidth = ([UIScreen mainScreen].bounds.size.width -20);
[label setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
//注意:这里只是设置了它的宽度和位置,(没有设置高!!!!!)
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.view).with.offset(10);
make.right.mas_equalTo(self.view).with.offset(-10);
make.top.mas_equalTo(self.view).with.offset(100);
}];
}
4.当使用masonry自定义cell的时候,如果cell的子控件尺寸需要动态变化的话,必须使用remake
14.layoutSubviews在以下情况下会被调用:
1、init初始化不会触发layoutSubviews
2、addSubview会触发layoutSubviews
3、设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化
4、滚动一个UIScrollView会触发layoutSubviews
5、旋转Screen会触发父UIView上的layoutSubviews事件
6、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件
15.点击屏幕得时候隐藏键盘,可以在这个方法里执行要隐藏或remove的view。
1.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch=[[event allTouches] anyObject];
if (touch.tapCount >=1) {
[self.view endEditing:YES];
}
}
2.你可以在任何地方加上这句话,可以用来统一收起键盘
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
3.iOS在当前屏幕获取第一响应
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
16.设置不自动黑屏
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
17.如何获取手机硬件信息?
[[UIDevice currentDevice] systemName];
[[UIDevice currentDevice] systemVersion];//os version
[[UIDevice currentDevice] uniqueIdentifier];
[[UIDevice currentDevice] model];
[[UIDevice currentDevice] name];
这样就实现了基本的使用,跟delegate类似,注意 addObserver时,需要写目标viewcontroller的实例,而不是self。
18.ios如何实现推送通知
http://blog.csdn.net/ios_che/article/details/7428413
19.ios9关于http 与HTTPS
在info.plist最后加上
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
定位功能
<key>NSLocationAlwaysUsageDescription</key>
<string>LocationDemo</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
20.在iOS上present一个半透明的viewController
(http://blog.csdn.net/jasonblog/article/details/17172969)
1. viewController.view.backgroundColor = [UIColor clearColor];
2. rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
3. [rootViewController presentModalViewController:viewController animated:YES];
4. 这里有两个点:一是设置modalPresentationStyle为UIModalPresentationCurrentContext,二是需要在rootViewController上操作。
21.创建渐变色图层
-(void)setGradientLayer2
{
// 创建渐变色图层
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = self.secView.bounds;
gradientLayer.colors = @[
(id)[UIColor cyanColor].CGColor,
(id)[UIColor blueColor].CGColor,
(id)[UIColor redColor].CGColor
];
// 设置渐变方向(0~1)
gradientLayer.startPoint = CGPointMake(0, 0);
gradientLayer.endPoint = CGPointMake(0, 1);
// 设置渐变色的起始位置和终止位置(颜色的分割点)
gradientLayer.locations = @[@(0.05f),@(0.70f),@(0.25f)];
gradientLayer.borderWidth = 0.0;
// 添加图层
[self.secView.layer addSublayer:gradientLayer];
}
22.svn 无法上传.a文件
去终端:cd 静态库所在的文件夹路径 按回车 svn add 你静态库的名字 .a也需要加上 然后回车
23.设置center和size,要先设置size再设置center!!!
24.让iOS应用直接退出
- (void)exitApplication {
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window;
[UIView animateWithDuration:1.0f animations:^{
window.alpha = 0;
} completion:^(BOOL finished) {
exit(0);
}];
}
25.获取 iOS 路径的方法
1.获取家目录路径的函数
NSString *homeDir = NSHomeDirectory();
2.获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
3.获取Documents目录路径的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
4.获取tmp目录路径的方法:
NSString *tmpDir = NSTemporaryDirectory();
26.修改Tabbar Item的属性
// 修改标题位置
self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);
// 修改图片位置
self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0);
// 批量修改属性
for (UIBarItem *item in self.tabBarController.tabBar.items) {
[item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica" size:19.0], NSFontAttributeName, nil]
forState:UIControlStateNormal];
}
// 设置选中和未选中字体颜色
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
//未选中字体颜色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} forState:UIControlStateNormal];
//选中字体颜色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor cyanColor]} forState:UIControlStateSelected];
27.UIAlertController
UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[controller addAction:[UIAlertAction actionWithTitle:@"收藏" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了[收藏]按钮");
}]];
[controller addAction:[UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了[举报]按钮");
}]];
[controller addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了[取消]按钮");
}]];
// [controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
// textField.textColor = [UIColor redColor];
// }];
[self.window.rootViewController presentViewController:controller animated:YES completion:nil];
28.控件的局部圆角问题
1.
CGRect rect = CGRectMake(0, 0, 100, 50);
CGSize radio = CGSizeMake(5, 5);//圆角尺寸
UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//创建shapelayer
masklayer.frame = button.bounds;
masklayer.path = path.CGPath;//设置路径
button.layer.mask = masklayer;
//2.设置cell为圆角
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:@selector(tintColor)]) {
if (tableView == self.tableView) {
// 圆角弧度半径
CGFloat cornerRadius = 20.f;
// 设置cell的背景色为透明,如果不设置这个的话,则原来的背景色不会被覆盖
cell.backgroundColor = UIColor.clearColor;
// 创建一个shapeLayer
CAShapeLayer *layer = [[CAShapeLayer alloc] init];
CAShapeLayer *backgroundLayer = [[CAShapeLayer alloc] init]; //显示选中
// 创建一个可变的图像Path句柄,该路径用于保存绘图信息
CGMutablePathRef pathRef = CGPathCreateMutable();
// 获取cell的size
CGRect bounds = CGRectInset(cell.bounds, 0, 0);
// CGRectGetMinY:返回对象顶点坐标
// CGRectGetMaxY:返回对象底点坐标
// CGRectGetMinX:返回对象左边缘坐标
// CGRectGetMaxX:返回对象右边缘坐标
// 这里要判断分组列表中的第一行,每组section的第一行,每组section的中间行
BOOL addLine = NO;
// CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
NSInteger num = [tableView numberOfRowsInSection:indexPath.section];
if (num == 1) {//1.当这组只有一行的时候,4个角读要是圆角
// 初始起点为cell的左下角坐标
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
// 起始坐标为左下角,设为p1,(CGRectGetMinX(bounds), CGRectGetMinY(bounds))为左上角的点,设为p1(x1,y1),(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点,设为p2(x2,y2)。然后连接p1和p2为一条直线l1,连接初始点p到p1成一条直线l,则在两条直线相交处绘制弧度为r的圆角。
//1.左下角为起点p,左上角为p1,顶部中点为p2,然后连接p1和p2为一条直线l1,连接初始点p到p1成一条直线l,则在两条直线相交处绘制弧度为r的圆角。
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
//2.顶部中点为p2,右上角为p3,右边中点为p4,连接p2p3与p3p4则在两条直线相交处绘制弧度为r的圆角。
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMinX(bounds), CGRectGetMidY(bounds), cornerRadius);
}else//2.这组不止1行
{
if (indexPath.row == 0) {
// 初始起点为cell的左下角坐标
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
// 起始坐标为左下角,设为p1,(CGRectGetMinX(bounds), CGRectGetMinY(bounds))为左上角的点,设为p1(x1,y1),(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点,设为p2(x2,y2)。然后连接p1和p2为一条直线l1,连接初始点p到p1成一条直线l,则在两条直线相交处绘制弧度为r的圆角。
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// 终点坐标为右下角坐标点,把绘图信息都放到路径中去,根据这些路径就构成了一块区域了
CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
addLine = YES;
} else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
// 初始起点为cell的左上角坐标
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// 添加一条直线,终点坐标为右下角坐标点并放到路径中去
CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
} else {
// 添加cell的rectangle信息到path中(不包括圆角)
CGPathAddRect(pathRef, nil, bounds);
addLine = YES;
}
}
// if (indexPath.row == 0) {
// // 初始起点为cell的左下角坐标
// CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
// // 起始坐标为左下角,设为p1,(CGRectGetMinX(bounds), CGRectGetMinY(bounds))为左上角的点,设为p1(x1,y1),(CGRectGetMidX(bounds), CGRectGetMinY(bounds))为顶部中点的点,设为p2(x2,y2)。然后连接p1和p2为一条直线l1,连接初始点p到p1成一条直线l,则在两条直线相交处绘制弧度为r的圆角。
// CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
// CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// // 终点坐标为右下角坐标点,把绘图信息都放到路径中去,根据这些路径就构成了一块区域了
// CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
// addLine = YES;
// } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
// // 初始起点为cell的左上角坐标
// CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
// CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
// CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
// // 添加一条直线,终点坐标为右下角坐标点并放到路径中去
// CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
// } else {
// // 添加cell的rectangle信息到path中(不包括圆角)
// CGPathAddRect(pathRef, nil, bounds);
// addLine = YES;
// }
// 把已经绘制好的可变图像路径赋值给图层,然后图层根据这图像path进行图像渲染render
layer.path = pathRef;
backgroundLayer.path = pathRef;
// 注意:但凡通过Quartz2D中带有creat/copy/retain方法创建出来的值都必须要释放
CFRelease(pathRef);
// 按照shape layer的path填充颜色,类似于渲染render
// layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
layer.fillColor = [UIColor whiteColor].CGColor;
// 添加分隔线图层
if (addLine == YES) {
CALayer *lineLayer = [[CALayer alloc] init];
CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
lineLayer.frame = CGRectMake(CGRectGetMinX(bounds), bounds.size.height-lineHeight, bounds.size.width, lineHeight);
// 分隔线颜色取自于原来tableview的分隔线颜色
lineLayer.backgroundColor = tableView.separatorColor.CGColor;
[layer addSublayer:lineLayer];
}
// view大小与cell一致
UIView *roundView = [[UIView alloc] initWithFrame:bounds];
// 添加自定义圆角后的图层到roundView中
[roundView.layer insertSublayer:layer atIndex:0];
roundView.backgroundColor = UIColor.clearColor;
//cell的背景view
//cell.selectedBackgroundView = roundView;
cell.backgroundView = roundView;
//以上方法存在缺陷当点击cell时还是出现cell方形效果,因此还需要添加以下方法
UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:bounds];
backgroundLayer.fillColor = tableView.separatorColor.CGColor;
[selectedBackgroundView.layer insertSublayer:backgroundLayer atIndex:0];
selectedBackgroundView.backgroundColor = UIColor.clearColor;
cell.selectedBackgroundView = selectedBackgroundView;
}
}
}
29.添加毛玻璃效果
- (void)setupBlur
{
// 1.初始化toolBar
UIToolbar *toolBar = [[UIToolbar alloc] init];
[self.image addSubview:toolBar];
toolBar.barStyle = UIBarStyleBlack;
// 2.添加约束
toolBar.translatesAutoresizingMaskIntoConstraints = NO;
[toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.image);
}];
}
2.
UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];
imageView.image = [UIImage imageNamed:@"肚肚.jpg"];
/*注:尽量避免将UIVisualEffectView对象的alpha值设置为小于1.0的值,
因为创建半透明的视图会导致系统在离屏渲染时去对UIVisualEffectView对象
及所有的相关的子视图做混合操作。这不但消耗CPU/GPU,也可能会导致许多效果
显示不正确或者根本不显示。*/
UIVisualEffectView *view = [[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
view.frame = CGRectMake(20, 20, CGRectGetWidth(self.view.frame)-40, CGRectGetHeight(self.view.frame)-40);
view.layer.cornerRadius = 5;
view.clipsToBounds = YES;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, CGRectGetWidth(self.view.frame) - 10, 45)];
label.text = @"fucking high";
[self.view addSubview:imageView];
[view.contentView addSubview:label];
[self.view addSubview:view];
30.修改名字
点击名字,右键,refactor,rename
31.pch文件
1.修改路径 build setting,apple LLVM 7.0 -Language,Prefix Header
使用路径:067/PrefixHeader.pch(相对路径)
全路径:/Users/bona/Desktop/IOS素材/模板/总结/搜索search/067/067/PrefixHeader.pch
2.格式
#ifdef __OBJC__ //在这里定义
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height
#endif
32.两种方法删除NSUserDefaults所有记录
//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
//方法二
- (void)resetDefaults
{
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict)
{
[defs removeObjectForKey:key];
}
[defs synchronize];
}
33.iOS 获取汉字的拼音
+ (NSString *)transform:(NSString *)chinese
{
//将NSString装换成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];
//将汉字转换为拼音(带音标)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
NSLog(@"%@", pinyin);
//去掉拼音的音标
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
NSLog(@"%@", pinyin);
//返回最近结果
return pinyin;
}
34.手动更改iOS状态栏的颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color
{
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
{
statusBar.backgroundColor = color;
}
}
2.[self setNeedsStatusBarAppearanceUpdate];
3.修改statusbar文字颜色
1.要修改为白色的需要在infoPlist里设置UIViewControllerBasedStatusBarAppearance为NO
2.[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
4.iOS加载启动图的时候隐藏statusbar 只需需要在info.plist中加入Status bar is initially hidden 设置为YES就好
35.取消UICollectionView的隐式动画
UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合cell的情况下(比如cell使用到了UIStackView)。
下面几种方法都可以帮你去除这些动画
//方法一
[UIView performWithoutAnimation:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];
//方法二
[UIView animateWithDuration:0 animations:^{
[collectionView performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:nil];
}];
//方法三
[UIView setAnimationsEnabled:NO];
[self.trackPanel performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
[UIView setAnimationsEnabled:YES];
}];
36.获取到webview的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
37.+ initialize 与 +load
+ initialize 这个方法会在 第一次初始化这个类之前 被调用,我们用它来初始化静态变量
+ load 方法会在加载类的时候就被调用,也就是 ios 应用启动的时候,就会加载所有的类,就会调用每个类的 + load 方法,它调用比main还早
如果你实现了+ load 方法,那么当类被加载时它会自动被调用。这个调用非常早。如果你实现了一个应用或框架的 + load,并且你的应用链接到这个框架上了,那么 + load 会在 main() 函数之前被调用。如果你在一个可加载的 bundle 中实现了 + load,那么它会在 bundle 加载的过程中被调用。
+ initialize 方法的调用看起来会更合理,通常在它里面写代码比在 + load 里写更好。+ initialize 很有趣,因为它是懒调用的,也有可能完全不被调用。类第一次被加载时,
+ initialize 不会被调用。类接收消息时,运行时会先检查 + initialize 有没有被调用过。如果没有,会在消息被处理前调用。
38.自动布局scrollview
1.在scrollview上先加一个contentView
2.设置它的布局
[self. contentView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(self.scrollView);
make.height.mas_equalTo(800);
}];
3.所有的子控件添加到contentView,并基于它来布局
4.注意:如果没有设置contentView的宽,子控件right要基于self.view,不然会看不到,这是由于scrollview的contentSize的width不确定
5. contentView的宽高决定了scrollview的contentSize的width和height
39.编辑状态
//1.成为第一响应者,叫起键盘
[self.textView becomeFirstResponder];
//2.放弃第一响应者,放下键盘
[self.textView resignFirstResponder];
//3.判断键盘是否弹起,是否在编辑状态
self.textView.isFirstResponder == YES
40.edgesForExtendedLayout
在iOS 7中,苹果引入了一个新的属性,叫做[UIViewController setEdgesForExtendedLayout:],它的默认值为UIRectEdgeAll。当你的容器是navigation controller时,默认的布局将从navigation bar的顶部开始。这就是为什么所有的UI元素都往上漂移了44pt。
self.edgesForExtendedLayout = UIRectEdgeNone;