代码记录1
1 .控制器的基类
- (void)viewDidLoad {
[super viewDidLoad];
[self setupViews];
//判断是否有上级页面,有的话再设置返回按钮
if ([self.navigationController.viewControllers indexOfObject:self] != 0) {
[self setupLeftBarButton];
}
}
- (void)setupViews {
//设置应用的背景色
self.view.backgroundColor = [UIColor lightGrayColor];
//不允许 viewController 自动调整,我们自己布局;如果设置为YES,视图会自动下移 64 像素
self.automaticallyAdjustsScrollViewInsets = NO;
}
#pragma mark - 自定义返回按钮
- (void)setupLeftBarButton {
//自定义 leftBarButtonItem ,UIImageRenderingModeAlwaysOriginal 防止图片被渲染
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
initWithImage:[[UIImage imageNamed:@"Back-蓝"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action:@selector(leftBarButtonClick)];
//防止返回手势失效
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
- (void)leftBarButtonClick {
[self.navigationController popViewControllerAnimated:YES];
}
2. 隐藏 navigationControll 左侧的返回按钮
self.navigationItem.hidesBackButton = YES;
self.navigationItem.rightBarButtonItem.customView.hidden = YES;
3. 改变 button 内部的图片以及文字的偏移量
//已经做了适配,各位可以根据需要做屏幕适配
self.changeSpecialistBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -lengthFit(16), 0, 0);
self.changeSpecialistBtn.imageEdgeInsets = UIEdgeInsetsMake(0, lengthFit(76), 0, 0);
4. tableView 滚动时自动收起键盘
self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
5. 判断上级页面是哪个页面
NSArray *array = self.navigationController.viewControllers;
6. 设置导航栏右部点击按钮,并添加点击事件
//添加文字按钮
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editor)];
self.navigationItem.rightBarButtonItem = rightBarButton;
// 添加图片按钮
UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"图片名"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonEvent)];
[self.navigationItem setRightBarButtonItem:rightBarBtn];
7. 给 view 添加手势,并加入点击事件
UITapGestureRecognizer *operationTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gotoCapture:)];
[self.operationView addGestureRecognizer:operationTap];
8. 设置图片拉伸
UIImage *bgImage = [UIImage imageNamed:@""];
bgImageView.image = [bgImage stretchableImageWithLeftCapWidth:15 topCapHeight:15];
9. 改变导航栏标题的颜色
UIColor *color = [UIColor cyanColor];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject: color forKey:NSForegroundColorAttributeName];
self.navigationController.navigationBar.titleTextAttributes = dictionary;
10. UISwitch控件,需要更改它的大小
//改变UISwitch 的大小,CGAffineTransformMakeScale(CGFloat x, CGFloat y) 对 view 的长和宽进行缩放,不改变 view 的中心点
self.orderSwitch.transform = CGAffineTransformMakeScale(0.7, 0.7);
// 改变 UISwitch 开启时的颜色
self.orderSwitch.onTintColor = KXColorBlue;
11. 加载本地的 HTML 文件
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *filePath = [resourcePath stringByAppendingPathComponent:@"serviceDescription.html"];
NSString *htmlString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString: htmlString baseURL: [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
12. iOS项目开发中用的一部分宏定义
// 屏幕尺寸
#define mainScreenWidth [UIScreen mainScreen].bounds.size.width
#define mainScreenHeight [UIScreen mainScreen].bounds.size.height
// 屏幕适配比例,分别为x,y,w,h
#define X(__x__) ((__x__) /375.0* mainScreenWidth)
#define Y(__y__) ((__y__) /667.0* mainScreenHeight)
#define W(__w__) ((__w__) /375.0* mainScreenWidth)
#define H(__h__) ((__h__) /667.0* mainScreenHeight)
//顶部状态栏和导航栏高度
#define kSafeAreaTopHeight (kStatusBarHeight +44)
//底部高度
#define kSafeAreaBottomHeight (kStatusBarHeight >20?34:0)
//顶部状态栏高度
#define kStatusBarHeight [[UIApplication sharedApplication] statusBarFrame].size.height
//底部安全距离
#define kTabBarHeight (kStatusBarHeight >20?83:49)
13. 自定义 leftBarButtonItem 返回按钮时,防止返回手势失效的办法
- (void)setupLeftBarButton {
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
initWithImage:[[UIImage imageNamed:@"Back-蓝"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action:@selector(leftBarButtonClick)];
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}
- (void)leftBarButtonClick {
[self.navigationController popViewControllerAnimated:YES];
}
14. 不允许 viewController 自动调整
self.automaticallyAdjustsScrollViewInsets = NO;
15. 去空格
//去掉两端的空格
[trimString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//去掉所有空格
[trimString stringByReplacingOccurrencesOfString:@" " withString:@""];
16. 判断字符串中是否包含非法字符
if ([self.searchText.text rangeOfString:@"'"].location != NSNotFound) {
//用封装好的提示框提示
[CommunityPublicClass showHUDwithLabelText:@"您输入的字符不合法" andDetailsLabelText:nil];
return;
}
17. 判断字符串是否为空
+ (BOOL)isBlankString:(NSString *)string {
if (string == nil || string == NULL) {
return YES;
}
if ([string isKindOfClass:[NSNull class]]) {
return YES;
}
if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
return YES;
}
return NO;
}
18. 导航栏的正确隐藏方法
[self.navigationController setNavigationBarHidden:YES animated:YES];
self.navigationController.navigationBarHidden = YES;
19. Xcode中的自定义的代码片段一般存放在:
~/Library/Developer/Xcode/UserData/CodeSnippets
20. masonry下的动画
修改约束后调用 [view.superview layoutIfNeeded];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(400);
}];
[view.superview layoutIfNeeded];//如果其约束还没有生成的时候需要动画的话,就请先强制刷新后才写动画,否则所有没生成的约束会直接跑动画
[UIView animateWithDuration:3 animations:^{
[view mas_updateConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(200);
}];
[view.superview layoutIfNeeded];//强制绘制
21. 跳到指定的设置界面
在URL Types添加 一个叫prefs的URL Schemes
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@“跳转不同界面对应的URLString"]]
蜂窝网络:prefs:root=MOBILE_DATA_SETTINGS_ID
VPN — prefs:root=General&path=Network/VPN
Wi-Fi:prefs:root=WIFI
定位服务:prefs:root=LOCATION_SERVICES
个人热点:prefs:root=INTERNET_TETHERING
关于本机:prefs:root=General&path=About
辅助功能:prefs:root=General&path=ACCESSIBILITY
飞行模式:prefs:root=AIRPLANE_MODE
锁定:prefs:root=General&path=AUTOLOCK
亮度:prefs:root=Brightness
蓝牙:prefs:root=General&path=Bluetooth
时间设置:prefs:root=General&path=DATE_AND_TIME
FaceTime:prefs:root=FACETIME
设置:prefs:root=General
键盘设置:prefs:root=General&path=Keyboard
iCloud:prefs:root=CASTLE
iCloud备份:prefs:root=CASTLE&path=STORAGE_AND_BACKUP
语言:prefs:root=General&path=INTERNATIONAL
定位:prefs:root=LOCATION_SERVICES
音乐:prefs:root=MUSIC
Music Equalizer — prefs:root=MUSIC&path=EQ
Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit
Network — prefs:root=General&path=Network
Nike + iPod — prefs:root=NIKE_PLUS_IPOD
Notes — prefs:root=NOTES
Notification — prefs:root=NOTIFICATIONS_ID
Phone — prefs:root=Phone
Photos — prefs:root=Photos
Profile — prefs:root=General&path=ManagedConfigurationList
Reset — prefs:root=General&path=Reset
Safari — prefs:root=Safari
Siri — prefs:root=General&path=Assistant
Sounds — prefs:root=Sounds
Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK
Store — prefs:root=STORE
Twitter — prefs:root=TWITTER
Usage — prefs:root=General&path=USAGE
Wallpaper — prefs:root=Wallpaper
22. 到Safari
NSString*url =@"http://www.baidu.com";//把http://带上
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:url]];
23. 到App Store
NSString* appstoreUrlString =@"itms-apps://itunes.apple.com/cn/app/hun-lian-dui-xiang/id1276460105?mt=8";
NSURL* url = [NSURLURLWithString:appstoreUrlString];
if([[UIApplicationsharedApplication]canOpenURL:url]) {
[[UIApplicationsharedApplication]openURL:url];
} else{
NSLog(@"can not open");
}
24. 评价APP
NSString*appstoreUrlString = [NSStringstringWithFormat:
@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@", @"1276460105"];
NSURL* url = [NSURLURLWithString:appstoreUrlString];
if([[UIApplicationsharedApplication]canOpenURL:url]) {
[[UIApplicationsharedApplication]openURL:url];
} else {
NSLog(@"can not open");
}
25. view抖动
CAKeyframeAnimation *keyAnima=[CAKeyframeAnimation animation];
keyAnima.keyPath=@"transform.rotation";
keyAnima.duration=0.1;
keyAnima.values=@[@(-angle2Radian(4)),@(angle2Radian(4)),@(-angle2Radian(4))];
keyAnima.repeatCount=MAXFLOAT;
keyAnima.fillMode=kCAFillModeForwards;
keyAnima.removedOnCompletion=NO;
for (int i = 0;i < _viewArray.count;i++) {
UIView * view = [_viewArray objectAtIndex:i];
UIButton * btn = [_buttonArray objectAtIndex:i];
[view addSubview:btn];
[view.layer addAnimation:keyAnima forKey:@"shake"];
NSArray *allGesture = view.gestureRecognizers;
for (UIGestureRecognizer *gesture in allGesture) {
[view removeGestureRecognizer:gesture];
}
}
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancleDelete)];
[backGroundView addGestureRecognizer:tap];
26. AFNetwoking的默认Content-Type是application/x-www-form-urlencodem。若服务器要求Content-Type为applicaiton/json,为了和服务器对应,就必须修改AFNetworking的Content-Type。
关于Content-Type的概念和Post常见的的提交数据方式请见博客:https://www.imququ.com/post/four-ways-to-post-data-in-http.html。
简单来说,服务器通过识别Content-Type来识别传送的数据类型,分辨传送的数据到底是文本,图片或者是其他。如果服务器不识别对应的Content-Type,那么就会返回错误415.
修改Content-Type代码如下:
AFHTTPRequestOperationManager*manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
27 时间转换
将日期时间转化为字符串
// 实例化NSDateFormatter
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置日期格式
[formatter setDateFormat:@"yyyy-mm-dd HH:mm:ss"];
// 获取当前日期
NSDate *currentDate = [NSDate date];
NSString *currentDateString = [formatter stringFromDate:currentDate];
NSLog(@"%@", currentDateString);
将时间字符串转换为日期
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 要转换的日期字符串
NSString *dateString = @"2011-05-03 23:11:40";
// 设置为UTC时区
// 这里如果不设置为UTC时区,会把要转换的时间字符串定为当前时区的时间(东八区)转换为UTC时区的时间
NSTimeZone *timezone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDate *someDay = [formatter dateFromString:dateString];
NSLog(@"%@", someDay);
时间格式
G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12,带前置0
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如02
d: 日,1-2位显示,如2,无前置0
EEE: 简写星期几,如Sun
EEEE: 全写星期几,如Sunday
aa: 上下午,AM/PM
H: 时,24小时制,0-23
HH: 时,24小时制,带前置0
h: 时,12小时制,无前置0
hh: 时,12小时制,带前置0
m: 分,1-2位
mm: 分,2位,带前置0
s: 秒,1-2位
ss: 秒,2位,带前置0
S: 毫秒
Z: GMT(时区)
28 打印所有的系统字体
// NSArray *familyNames = [UIFont familyNames];
// for(NSString *familyName in familyNames ) {
// NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
// for(NSString *fontName in fontNames ){
// printf( "\tFont: %s \n", [fontName UTF8String] );
// }
// }
29 旋转文字
button.titleLabel.transform =CGAffineTransformMakeRotation(M_PI_4);
30. 阴影
UIView的阴影设置主要通过UIView的layer的相关属性来设置
阴影的颜色
imgView.layer.shadowColor = [UIColor blackColor].CGColor;
阴影的透明度
imgView.layer.shadowOpacity = 0.8f;
阴影的圆角
imgView.layer.shadowRadius = 4.f;
阴影偏移量
imgView.layer.shadowOffset = CGSizeMake(4,4);
即使偏移量为(0,0)时,围绕view的四周依然能看到一定阴影。
当我们不设置阴影的偏移量的时候,默认值为(0,-3),既阴影有3个点的向上偏移量。为什么是向上偏移呢?这好像有点不合常理,其实这是由‘历史原因’造成的,阴影最先是在MacOS平台上出现的,默认是向下偏移3个点,我们知道MacOS的坐标系统和iOS坐标系统y轴方向是相反的,所以在iOS系统中由于y轴方向的改变就变成了默认向上偏移3个点。
阴影的路径
除了通过上面的操作,我们还可以设定阴影的路径
路径阴影
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(-5, -5)];
//添加直线
[path addLineToPoint:CGPointMake(paintingWidth /2, -15)];
[path addLineToPoint:CGPointMake(paintingWidth +5, -5)];
//设置阴影路径
imgView.layer.shadowPath = path.CGPath;
31 去除数组中重复的对象
NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self”];
32.给一个view截图
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
33.设置navigationBar上的title颜色和大小
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}]
34. 在window加label
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height + 88, [UIScreen mainScreen].bounds.size.width, 60)];
label.backgroundColor = [UIColor blackColor];
label.text = msg;
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:24];
[[UIApplication sharedApplication].keyWindow addSubview:label];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[label removeFromSuperview];
});