iOS開發中遇到的常用的小知識
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.
[animation setAutoreverses:NO];
//動畫時間
animation.duration=0.9;
animation.delegate=self;
[niceView.layeraddAnimation:animation forKey:@"scale"];
//結束;
3、設定導航欄的背景圖片
[[UINavigationBarappearance] setBackgroundImage:[UIImageimageNamed:@"nav_bg_ios7.png"]forBarMetrics:
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、layO