1、launchImage如果不设置,或是图片尺寸设置不正确,app启动时会出现短暂的黑屏
2、启动动画简单示例,在app delegate中写
//圖片擴大淡出的效果开始;
//设置一个图片;
niceView = [[UIImageViewalloc] initWithFrame:[UIScreenmainScreen].bounds];
niceView.tag=11;
niceView.image = [UIImageimageNamed:@"launch4.7.png"];
//添加到场景
[self.windowaddSubview:niceView];
//放到最顶层;
[self.windowbringSubviewToFront:niceView];
CABasicAnimation *animation=[CABasicAnimationanimationWithKeyPath:@"transform.scale"];
niceView.layer.anchorPoint =CGPointMake(.5,.5);
animation.fromValue = @1.0f;
animation.toValue = @1.3f;
animation.fillMode=kCAFillModeForwards;
animation.removedOnCompletion =NO;
[animation setAutoreverses:NO];
//动画时间
animation.duration=0.9;
animation.delegate=self;
[niceView.layeraddAnimation:animation forKey:@"scale"];
//结束;
3、设置导航栏的背景图片
[[UINavigationBarappearance] setBackgroundImage:[UIImageimageNamed:@"nav_bg_ios7.png"]forBarMetrics:UIBarMetricsDefault];
4、设置返回按钮的事件
UIBarButtonItem *backButton = [[UIBarButtonItemalloc]
initWithTitle:@""
style:UIBarButtonItemStylePlaintarget:nilaction:nil];
[self.navigationItemsetBackBarButtonItem:backButton];
5、判断字符串是否为空
+ (BOOL) isBlankString:(NSString *)string {
if (string == nil || string == NULL) {
return YES;
}
if ([string isKindOfClass:[NSNullclass]]) {
return YES;
}
if ([[stringstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]] length]==0) {
return YES;
}
return NO;
}
6、ShareSDK分享心得
1、首先需要申请appkey和appsecret
2、下载SDK,在app delegate中按照文档进行配置(有简洁版和标准版两种)
3、导入相关的frameworks and libraries,加入URL types的URL Schemes,如果是QQ的话需要大写,微信和微博等用小写;在info.plist中添加一个LSApplicationQueriesSchemes字段,里面填需要分享的白名单
4、可以自定义分享样式,也可以用自带的分享样式(由于AppStore审核要求,如果手机上没有安装该app则不要将该app显示在分享样式中)
[ShareSDKisClientInstalled:SSDKPlatformTypeSinaWeibo]
5、分享的内容,包括title、image、content、url等
6、由于weiboSDK中包含有广告框架,但是实际上并没有使用广告,这样直接提交到AppStore的话会被拒绝,解决办法有两种(http://wiki.mob.com/idfa%e7%9a%84%e6%a3%80%e6%b5%8b%e5%92%8c%e9%80%9a%e8%bf%87%e5%ae%a1%e6%a0%b8/详情看看我们的这个文档),一种是通过第三方添加一个广告,另一种是删除微博sdk,不调用微博的原生sdk,可以实现app内分享,但是无法跳转到客户端分享。
7、 //印象笔记分为国内版和国际版,注意区分平台
//设置印象笔记(中国版)应用信息
caseSSDKPlatformTypeYinXiang:
//设置印象笔记(国际版)应用信息
caseSSDKPlatformTypeEvernote:
[appInfo SSDKSetupEvernoteByConsumerKey:@"lvlvlaw"
consumerSecret:@"a6731d6bd22aef5e"
sandbox:NO];
当修改为产品环境的时候,记得最后的sandbox选项设置为NO
7、保持原来的长宽比,生成一个缩略图
+(UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
UIImage *newimage;
if (nil == image)
{
newimage = nil;
}
else
{
CGSize oldsize = image.size;
CGRect rect;
if (asize.width/asize.height > oldsize.width/oldsize.height)
{
rect.size.width = asize.height*oldsize.width/oldsize.height;
rect.size.height = asize.height;
rect.origin.x = (asize.width - rect.size.width)/2;
rect.origin.y =0;
}
else
{
rect.size.width = asize.width;
rect.size.height = asize.width*oldsize.height/oldsize.width;
rect.origin.x =0;
rect.origin.y = (asize.height - rect.size.height)/2;
}
UIGraphicsBeginImageContext(asize);
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColorclearColor] CGColor]);
UIRectFill(CGRectMake(0,0, asize.width, asize.height));//clear background
[image drawInRect:rect];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newimage;
}
8、极光推送心得
1、在极光推送平台上面添加应用,需要开发证书和生产证书,两者都是p12格式的
2、下载最新的SDK,在app delegate中按照文档上面的来进行设置。
if ([[UIDevicecurrentDevice].systemVersionfloatValue] >= 8.0) {
//可以添加自定义categories
[APServiceregisterForRemoteNotificationTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert)categories:nil];
} else {
//categories 必须为nil
[APServiceregisterForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)
categories:nil];
}
[APServicesetupWithOption:launchOptions];
[APServicesetLogOFF];//关闭日志
[APServiceregisterDeviceToken:deviceToken];
NSLog(@"registrationID:%@",[APServiceregistrationID]);
[APServicehandleRemoteNotification:userInfo];
application.applicationState ==UIApplicationStateActive//判断是在前台还是后台,分别做不同的处理
3、需要在xcode中开启推送服务
4、需要设置app图标上的badgeValue,按照需求进行设置。
[UIApplicationsharedApplication].applicationIconBadgeNumber;
[APServiceresetBadge];//服务器端badge的值清零
5、推送跳转的设置,根据推送的内容判断跳转到app的相应页面。
9、单例的写法
static SingeData *sharedObj = nil;
+ (SingeData *)sharedInstance{
@synchronized(self) {
if (sharedObj ==nil) {
sharedObj = [[selfalloc]init];
}
}
returnsharedObj;
}
10、属性监听(确保两点,一是属性,二是用”.”操作调用属性)
给属性添加监听
[selfaddObserver:selfforKeyPath:@"labelViewsheight"options:NSKeyValueObservingOptionNewcontext:NULL];
//当属性的值发生变化时,自动调用此方法,做相应的处理
/* listen for changes to the earthquake list coming from our app delegate. */
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
}
11、获取<>括起来的以字母“i”开头的字符
NSString *urlString =@"dadfasdfdshttp://www.baidu.com<img jkljfkldsal>";
NSError *error;
NSRegularExpression *regex = [NSRegularExpressionregularExpressionWithPattern:@"<i[^>]+>"options:0error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch = [regexfirstMatchInString:urlString options:0 range:NSMakeRange(0, [urlStringlength])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
NSString *result = [urlString substringWithRange:resultRange];
NSLog(@"%@",result);
}
}
12、画直线,需要在drawRect中写,用来自定义控件画线
CGContextRef ctx =UIGraphicsGetCurrentContext();
//设置颜色,仅填充4条边
CGContextSetStrokeColorWithColor(ctx, [[UIColorlightGrayColor] CGColor]);
//设置线宽为1
CGContextSetLineWidth(ctx,0.5);
CGContextMoveToPoint(ctx,0, self.frame.size.height-0.5);
CGContextAddLineToPoint(ctx,self.frame.size.width-0.5,self.frame.size.height-0.5);
CGContextClosePath(ctx);
CGContextStrokePath(ctx);
13、iOS上如何让按钮文本左对齐问题
- // button.titleLabel.textAlignment = NSTextAlignmentLeft; 这句无效
- button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
- button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
14.通过scheme打开app接受参数
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
NSString * text=[[urlhost]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"text:%@",text);
return YES;
}
15、打开获取系统通讯录
导入头文件
#import <AddressBook/AddressBook.h>
//提供通讯录的界面功能
#import <AddressBookUI/AddressBookUI.h>
代理
ABPeoplePickerNavigationControllerDelegate
- (void)openAddressBook{
//1.创建通讯录界面的对象。不用初始化跟视图控制器,以为它自带的有通讯录这个跟视图控制器
ABPeoplePickerNavigationController *peoplePicker =[[ABPeoplePickerNavigationControlleralloc] init];
//设置代理
//注意:这里不要直接设置delegate
peoplePicker.peoplePickerDelegate = self;
//模态弹出
[selfpresentViewController:peoplePicker animated:YEScompletion:nil];
}
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
//获取联系人的姓名:
NSString* name = (__bridgeNSString* )ABRecordCopyCompositeName(person);
// _nameLabel.text = name;
//获取联系人的电话:
//获取到的multiValueRef是某个种类信息的集合
//1.某个联系人 2.某个联系人的某个种类的信息
ABMultiValueRef multiValueRef =ABRecordCopyValue(person,kABPersonPhoneProperty);
//获取到这个种类信息的个数
//int count = ABMultiValueGetCount(multiValueRef);
//NSLog(@"count = %d",count);
NSString* phone = (__bridgeNSString* )ABMultiValueCopyValueAtIndex(multiValueRef,0);
NSLog(@"name: %@ \n phoneNumber:%@",name,phone);
// _phoneLabel.text = phone;
self.customView.phoneTextField.text = phone;
self.customView.phoneNumber = phone;
}
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
}
16、设置导航栏按钮
UIBarButtonItem *leftItem = [[UIBarButtonItemalloc] initWithCustomView:backBtn];
self.navigationItem.leftBarButtonItem = leftItem;
17、检测网络状态
[[AFNetworkReachabilityManagersharedManager]startMonitoring];
// 连接状态回调处理
/* AFNetworking的Block内使用self须改为weakSelf,避免循环强引用, 无法释放 */
__weak typeof(self) weakSelf =self;
[[AFNetworkReachabilityManagersharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
switch (status)
{
caseAFNetworkReachabilityStatusUnknown:
// 回调处理
weakSelf.networkReachability = [NSNumbernumberWithInt:3];
[Utils showMsg:@"当前网络为未知网络,请谨慎!!!"];
break;
caseAFNetworkReachabilityStatusNotReachable:
// 回调处理
weakSelf.networkReachability = [NSNumbernumberWithInt:0];
[weakSelf networkReachabilityMessage:@"您网络已断开,请检查你的网络"];
break;
caseAFNetworkReachabilityStatusReachableViaWWAN:
// 回调处理
weakSelf.networkReachability = [NSNumbernumberWithInt:1];
[weakSelf networkReachabilityMessage:@"您已切换到蜂窝移动网络"];
break;
caseAFNetworkReachabilityStatusReachableViaWiFi:
// 回调处理
weakSelf.networkReachability = [NSNumbernumberWithInt:2];
[weakSelf networkReachabilityMessage:@"您已切换到WiFi"];
break;
default:
break;
}
}];
}
18.通知中心传值
添加监听
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(click:)name:@"hello"object:nil];
发送通知
[[NSNotificationCenterdefaultCenter]postNotificationName:@"hello"object:@"helloss"];
获取传值
- (void)click:(NSNotification *)noti{
NSLog(@"%@",noti.object);
}
19、sharesdk判断手机上是否安装某个app
[ShareSDKisClientInstalled:SSDKPlatformTypeSinaWeibo];
20、降低 状态栏显示的优先级,以实现在状态栏位置显示特效的目的
AppDelegate *app = [UIApplicationsharedApplication].delegate;
app.window.windowLevel =UIWindowLevelAlert;
优先级恢复正常
app.window.windowLevel =UIWindowLevelNormal;
21、监听键盘的显示与消失
//增加监听,当键盘出现或者改变时收出消息
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];
//增加监听,当键盘退出时收出消息
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];
22、屏幕截屏
- (UIImage *)capture
{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,self.view.opaque,0.0);
[self.view.layerrenderInContext:UIGraphicsGetCurrentContext()];
UIImage * img =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
23、滑动返回效果实现原理
继承UINavigationController,写一个子类,在子类中实现滑动返回手势;在self.view上面添加pan手势,另外在self.view下面放一个view,view上面添加一张截屏图片(截屏图片是当push的时候截得屏幕,也就四push之前的界面)(代码:[self.view.superviewinsertSubview:self.mBgViewbelowSubview:self.view]);监听滑动手势的状态(recoginzer.state == UIGestureRecognizerStateBegan、UIGestureRecognizerStateEnded、UIGestureRecognizerStateCancelled),在不同的过程中实现不同的方法。另外还要注意两个参数#define CJOffsetFloat 0.65//拉伸参数
#define CJOffetDistance 110//最小回弹距离
24、
1、layOutSubViews可以在自己定制的视图中重载这个方法,用来调整子视图的尺寸和位置。
2、UIView的setNeedsDisplay和setNeedsLayout方法。首先两个方法都是异步执行的。而setNeedsDisplay会调用自动调用drawRect方法,这样可以拿到UIGraphicsGetCurrentContext,就可以画画了。而setNeedsLayout会默认调用layoutSubViews,就可以处理子视图中的一些数据。
宗上所诉,setNeedsDisplay方便绘图,而layoutSubViews方便出来数据。
1,UIView的setNeedsDisplay和setNeedsLayout方法
首先两个方法都是异步执行的。而setNeedsDisplay会调用自动调用drawRect方法,这样可以拿到 UIGraphicsGetCurrentContext,就可以画画了。而setNeedsLayout会默认调用layoutSubViews,
就可以 处理子视图中的一些数据。
综上所诉,setNeedsDisplay方便绘图,而layoutSubViews方便出来数据。
layoutSubviews在以下情况下会被调用:
1、init初始化不会触发layoutSubviews。
2、addSubview会触发layoutSubviews。
3、设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化。
4、滚动一个UIScrollView会触发layoutSubviews。
5、旋转Screen会触发父UIView上的layoutSubviews事件。
6、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件。
7、直接调用setLayoutSubviews。
drawRect在以下情况下会被调用:
1、如果在UIView初始化时没有设置rect大小,将直接导致drawRect不被自动调用。drawRect调用是在Controller->loadView, Controller->viewDidLoad 两方法之后掉用的.所以不用担心在控制器中,这些View的drawRect就开始画了.这样可以在控制器中设置一些值给View(如果这些View draw的时候需要用到某些变量值).
2、该方法在调用sizeToFit后被调用,所以可以先调用sizeToFit计算出size。然后系统自动调用drawRect:方法。
3、通过设置contentMode属性值为UIViewContentModeRedraw。那么将在每次设置或更改frame的时候自动调用drawRect:。
4、直接调用setNeedsDisplay,或者setNeedsDisplayInRect:触发drawRect:,但是有个前提条件是rect不能为0。
以上1,2推荐;而3,4不提倡
drawRect方法使用注意点:
1、若使用UIView绘图,只能在drawRect:方法中获取相应的contextRef并绘图。如果在其他方法中获取将获取到一个 invalidate的ref并且不能用于画图。drawRect:方法不能手动显示调用,必须通过调用setNeedsDisplay 或者 setNeedsDisplayInRect,让系统自动调该方法。
2、若使用calayer绘图,只能在drawInContext: 中(类似于drawRect)绘制,或者在delegate中的相应方法绘制。同样也是调用setNeedDisplay等间接调用以上方法
3、若要实时画图,不能使用gestureRecognizer,只能使用touchbegan等方法来掉用setNeedsDisplay实时刷新屏幕
25、调整屏幕亮度
[[UIScreen mainScreen] setBrightness: value];value的值在0-1之间
26、tableview隐藏多余的分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView
{
UIView *view =[ [UIViewalloc]init];
view.backgroundColor = [UIColorclearColor];
[tableView setTableFooterView:view];
}
27、图片转文件流
NSData *tempData = UIImageJPEGRepresentation(_tempImage, 1);
28、iOS7滑动返回实现
if ([nav respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
nav.interactivePopGestureRecognizer.delegate = nil; }
29、给Button设置背景图片的时候button的类型要设置为自定义的,否则会出现蓝边
30.UILabel字体加粗 IOS
加粗;
[UILabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
加粗并且倾斜
[UILabel setFont:[UIFont fontWithName:@"Helvetica-BoldOblique" size:20]];
31、当一个viewcontroller中有多个tableview的时候需要添加下面一行代码
self.automaticallyAdjustsScrollViewInsets =NO;
32、UILabel设置行间距等属性:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:contentLabel.text];;
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
[paragraphStyle setLineSpacing:5];
[attributedString addAttribute:NSParagraphStyleAttributeNamevalue:paragraphStyle range:NSMakeRange(0, contentLabel.text.length)];
contentLabel.attributedText = attributedString;
//调节高度
CGSizesize = CGSizeMake(width,500000);
CGSize labelSize = [contentLabel sizeThatFits:size];
33、本地化存储的时候不能存储Model,需要进行归档解归档操作
例如:- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:@(self.CategoryId)forKey:@"CategoryId"];
[aCoder encodeObject:self.CategoryNameforKey:@"CategoryName"];
[aCoder encodeObject:@(self.CategoryType)forKey:@"CategoryType"];
[aCoder encodeObject:@(self.CountNum)forKey:@"CountNum"];
[aCoder encodeObject:@(self.isSelect)forKey:@"isSelect"];
}
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [superinit];
if (self) {
self.CategoryId = [[coderdecodeObjectForKey:@"CategoryId"]integerValue];
self.CategoryName = [coderdecodeObjectForKey:@"CategoryName"];
self.CountNum = [[coderdecodeObjectForKey:@"CountNum"]integerValue];
self.CategoryType = [[coderdecodeObjectForKey:@"CategoryType"]integerValue];
self.isSelect = [[coderdecodeObjectForKey:@"isSelect"]boolValue];
}
return self;
}
34、获取系统时间
NSDate * senddate=[NSDatedate];
NSDateFormatter *dateformatter=[[NSDateFormatteralloc] init];
[dateformatter setDateFormat:@"HH"];
NSDateFormatter *dateformatter1=[[NSDateFormatteralloc] init];
[dateformatter1 setDateFormat:@"mm"];
NSString * locationString=[dateformatter stringFromDate:senddate];
NSString *st = [dateformatter1 stringFromDate:senddate];
NSLog(@"hour:%@ minute:%@",locationString,st);
35、textfield限制输入字符的长度
[self.nameTextFieldaddTarget:selfaction:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
- (void)textFieldDidChange:(UITextField *)textField{
if (textField == self.nameTextField) {
if (textField.text.length >10) {
textField.text = [textField.textsubstringToIndex:10];
}
}
}