您的位置:首页 > 移动开发 > IOS开发

iOS Record

2016-01-20 00:00 519 查看
摘要: iOS开发笔记

0. Debug下打印 Release下不打印

#ifdef DEBUG
#define DLog(fmt, ...) {NSLog((@"%s " fmt), __PRETTY_FUNCTION__, ##__VA_ARGS__);}
#else
#define DLog(...)
#endif

#ifdef DEBUG
#define Log(...) NSLog(__VA_ARGS__)
#else
#define Log(...)
#endif

1. 切换标签时 要tableView置顶

//设置偏移量用此动画
[UIView animateWithDuration:.01 animations:^{
[self.myTableView setContentOffset:CGPointZero];
}];

//发现animated设置无效
[self.myTableView setContentOffset:CGPointZero animated:YES];

2. Xcode中设置可与itunes共享文件

通过在app工程的Info.plist文件中指定UIFileSharingEnabled关键字,并将其值设置为YES

3. 使用 get / post 请求参数带中文时

//使用UTF-8对中文参数进行编码
NSString *param = [@"雕刻时光" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//请求url请使用拼接后的 urlString。
NSString *baseUrl = [NSString stringWithFormat:@"http://api.qingfanqie.com/Search/
TotalNumberOfLibrarySearch/%@/233/000014", param];

NSLog(@"%@:%@", [@"/Search/雕刻时光/" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
, [@"/Search/%E9%9B%95%E5%88%BB%E6%97%B6%E5%85%89/" stringByReplacingPercentEscapesUsingEncoding:
NSUTF8StringEncoding]);

//log
2014-05-23 14:21:54.835 GreenTomato[2422:60b] /Search/%E9%9B%95%E5%88%BB%E6%97%B6%E5%85%89:/Search/雕刻时光/

4. array dic 写入本地文件

//宏定义文件路径
#define kAppMarkBookFilePath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"appMarkBookFile.plist"]

[self.tableItems writeToFile:kAppMarkBookFilePath atomically:YES];

5. 数组与字符串转换

NSString *str = @"ab,cd,ef,g123";

//str -> array
NSArray *array = [str componentsSeparatedByString:@","];

//array-> str
str = [array componentsJoinedByString:@"."];

NSLog(@"array:%@, str:%@", array, str);

//打印
array:(
ab,
cd,
ef,
g123
), str:ab.cd.ef.g123

6. button圆角 文字左对齐

button 设置圆角
//边框
_btnLeft.layer.borderColor = [[UIColor blackColor] CGColor];
_btnLeft.layer.borderWidth = 1.0f;

//弧度
_btnLeft.layer.cornerRadius = 5.0f;
_btnLeft.layer.masksToBounds = YES;

[_btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];//左对齐

7. 隐藏系统文件 命令行

defaults write com.apple.finder AppleShowAllFiles -bool true

defaults write com.apple.finder AppleShowAllFiles -bool false

8. 写个枚举

typedef enum : NSUInteger {
ShareButtonTypeWechat = 11,
ShareButtonTypeQQ,
ShareButtonTypeSina,
ShareButtonTypePyq,
ShareButtonTypeCode

} ShareButtonType;

//
if (btn.tag == ShareButtonTypeQQ) {}

9. 定义通知 notification

//.h
extern NSString *const kNotificationHiddenAlarm;

//.m
NSString *const kNotificationHiddenAlarm = @"kNotificationHiddenAlarm";

10. 点击手势对应的view

/**
*  4个view都添加了tap手势 取出tap点击的view-tag区别是哪个view触发
*/
- (void)homePageViewTap:(UITapGestureRecognizer *)gesture {
UIView *view = [gesture view];
NSLog(@"view.tag = %d", (int)view.tag);
}

11. 随机数

arc4random_uniform(255)

12. 计算两个NSDate是否处于同一天的算法,无需使用calendar接口,无需format为字符串,兼容时区

double timezoneFix = [NSTimeZone localTimeZone].secondsFromGMT;
if (
(int)(([nowDate timeIntervalSince1970] + timezoneFix)/(24*3600)) -
(int)(([lastDate timeIntervalSince1970] + timezoneFix)/(24*3600))
== 0)
{
return YES;
}

13. 根据类名push

Class viewControllerClass = NSClassFromString(self.myClassNames2[indexPath.row]);
UIViewController *vc = [[viewControllerClass alloc] init];
if (vc) {
[self.navigationController pushViewController:vc animated:YES];
}

14. 给 UILabel行间距

NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:testString];
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setLineSpacing:15];

[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [testString length])];

[cLabel setAttributedText:attributedString1];
[cLabel sizeToFit];

15. 改变UITextField光标颜色

//影响所有textField
[[UITextField appearance] setTintColor:xx]

//单个textField
textField.tintColor = xx;

16. 设置导航栏样式

/**
*  网络风火轮
*/
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

/**
*  调节亮度
*/
[[UIScreen mainScreen] setBrightness:.4];

/**
*  不锁屏
*/
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

/**
*  状态栏白色字体 UIStatusBarStyleLightContent
plist添加 UIViewControllerBasedStatusBarAppearance 键值
*/
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];

/**
*  导航栏颜色
*/
self.navigationController.navigationBar.barTintColor = kColor(0x333333);

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
} else {
}

[self.navigationController.navigationBar setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor], UITextAttributeTextColor,
kColor(0x333333), UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, 0)], UITextAttributeTextShadowOffset,
kFontTitleSize(17), UITextAttributeFont,nil]];

17. uiscrollview autolayout不滚动

将设置sv contsize放到 viewDidAppear(这个函数会在autoLayout之后被执行)

执行顺序: viewDidLoad-updateViewConstraints-viewDidAppear

18. 自定义了导航栏左按钮, 同时要用到系统的滑动返回

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
self.edgesForExtendedLayout = UIRectEdgeNone;

//右滑shoushi
UIScreenEdgePanGestureRecognizer *edgePanGes = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleEdgePanGesture:)];
edgePanGes.edges = UIRectEdgeAll;
edgePanGes.delegate = self;
self.navigationController.interactivePopGestureRecognizer.delegate = self;

[self.view addGestureRecognizer:edgePanGes];
}

- (void)handleEdgePanGesture:(UIScreenEdgePanGestureRecognizer *)gesture {
[self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
if (1 == self.navigationController.viewControllers.count) return NO;
return YES;
}

19. AFNetworking发起多个网络请求, 都返回后才刷新UI可以这么做

@property (nonatomic, retain) dispatch_group_t serviceGroup;

- (void)initData {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"%@", [NSThread currentThread]);

// 创建gcd group
_serviceGroup = dispatch_group_create();

// 将任务放入 group中
dispatch_group_enter(_serviceGroup);
// 网络任务1
NSLog(@"Group任务One");
[self.engine getRegistMode];

dispatch_group_enter(_serviceGroup);
// 网络任务1
NSLog(@"Group任务Two");
[self.engine homePageGetBanner];

dispatch_group_notify(_serviceGroup, dispatch_get_main_queue(), ^{
// 任务全部完成处理
NSLog(@"完成");
});
});
}

//AFN 回调

- (void)httpRequestEngineDidSuccessWithObject:(id)object bySelector:(SEL)selector {
[super httpRequestEngineDidSuccessWithObject:object bySelector:selector];

//将任务移出group
dispatch_group_leave(_serviceGroup);
}

20. GCD 多个任务不需要回调返回, 第2种doSomexxx放到后台执行了

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
for(id obj in array)
dispatch_group_async(group, queue, ^{
[self doSomethingIntensiveWith:obj];
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_release(group);

[self doSomethingWith:array];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
for(id obj in array)
dispatch_group_async(group, queue, ^{
[self doSomethingIntensiveWith:obj];
});
dispatch_group_notify(group, queue, ^{
[self doSomethingWith:array];
});
dispatch_release(group);

21. //百度地图只显示网格 不显示地图 --> 百度地图应用与项目的bundle id要一致

22. 某些页面需要横屏 在if里面列出需要横屏的vc类名

#import "rootVC.h"

@implementation rootVC

- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];

//PushVC FirstPushVC SecondPushVC ThirdPushVC
UIViewController *vc = self.navigationController.topViewController;
if ([vc isKindOfClass:NSClassFromString(@"IOS8TableViewController")]
|| [vc isKindOfClass:NSClassFromString(@"PushVC")]
|| [vc isKindOfClass:NSClassFromString(@"SecondPushVC")]) {
[[UIDevice currentDevice] setValue:@(UIDeviceOrientationLandscapeLeft) forKey:@"orientation"];
} else {
[[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
}

[[self class] attemptRotationToDeviceOrientation];
}

@end

23. UIImageView添加圆角

最直接的方法就是使用如下属性设置:

imgView.layer.cornerRadius = 10;
//这是离屏渲染(off-screen-rendering),消耗性能的**
imgView.clipsToBounds = YES;

给UIImage添加生成圆角图片的扩展API:这是on-screen-rendering

- (UIImage *)imageWithCornerRadius:(CGFloat)radius {
CGRect rect = (CGRect){0.f, 0.f, self.size};

UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),
[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());

[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return image;
}

24. pod多个第三方框架不需要bitcode, 可在podfile文件添加如下代码再pos install

post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
end
end
end

25. pureLayout布局方法

/**
withFixedSpacing:(CGFloat)spacing    :
每个控件的间距 若shouldSpaceInsets为YES,则头尾2控件距离父试图间距一致等同spacing值
若shouldSpaceInsets为NO,则头尾2控件距离父试图间距都为0
insetSpacing:(BOOL)shouldSpaceInsets :
头尾2控件距离父试图间距是否相等
*/
[btns autoDistributeViewsAlongAxis:ALAxisVertical alignedTo:ALAttributeVertical withFixedSpacing:50 insetSpacing:YES matchedSizes:YES];

26.

27.

28.

29.

30.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: