iOS中的一些小功能和技巧

1:撥打電話

方式一
  NSURL *url = [NSURL URLWithString:@"tel://4000-916-416"];
            [[UIApplication sharedApplication] openURL:url];
方式一是最直接撥打電話,存在一個缺點:打電話結(jié)束之后,會停留在通訊錄界面,不會跳轉(zhuǎn)到APP界面
方式二
 NSURL *url = [NSURL URLWithString:@"telprompt://4000-916-416"];
            [[UIApplication sharedApplication] openURL:url];
方式二,會彈出一個提示框,我們的電話號碼是4-3-4的格式,但提示框的號碼是3-3-4,而且這個存在一個問題是,訪問私有的API,很可能存在上架時候被拒
Snip20160822_5.png
方式三:
  if (_webView == nil) {
                _webView = [[UIWebView alloc] initWithFrame:CGRectZero];
            }
            [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel://4000-916-416"]]];
方式三:這個是通過內(nèi)嵌一個UIWebView來實現(xiàn),打完電話后,會回到應(yīng)用

2.發(fā)短信

第一種方法
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://110"]];
第一種方法存在的缺點:不能回到應(yīng)用,而且不能指定內(nèi)容
第二種方法,利用第三方框架

1、導(dǎo)入 MessageUI.framework 框架。
2、引入頭文件 #import <MessageUI/MessageUI.h> ,實現(xiàn)代理方法 <MFMessageComposeViewControllerDelegate> 。

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {

    [self dismissViewControllerAnimated:YES completion:nil];

    switch (result) {
        case MessageComposeResultCancelled:
            NSLog(@"取消發(fā)送");
            break;

        case MessageComposeResultSent:
            NSLog(@"已發(fā)送");
            break;

        case MessageComposeResultFailed:
            NSLog(@"發(fā)送失敗");
            break;

        default:
            break;
    }
}

3.發(fā)送短信方法

- (void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
    if([MFMessageComposeViewController canSendText]) {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        // --phones發(fā)短信的手機號碼的數(shù)組,數(shù)組中是一個即單發(fā),多個即群發(fā)。
        controller.recipients = phones;
        // --短信界面 BarButtonItem (取消按鈕) 顏色
        controller.navigationBar.tintColor = [UIColor redColor];
        // --短信內(nèi)容
        controller.body = body;
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
    }
    else
    {

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                                 message:@"該設(shè)備不支持短信功能"
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:alertAction];

        [self presentViewController:alertController animated:YES completion:nil];

    }
}

4.回調(diào)

 [self showMessageView:[NSArray arrayWithObjects:@"110", nil] title:@"test" body:@"謝謝瀏覽凡塵一笑的文章,如果喜歡請收藏,關(guān)注,小編會不定時為您更新"];

3.更換NSLog

我們在開發(fā)階段經(jīng)常會使用NSLog來做打印調(diào)試,一個項目下來就存在好多打印,但是在發(fā)布階段是需要將這些打印刪除的,由于我們在開發(fā)中很多打印自己有時候都很難找得到,所以我們可以自己用一個來代替NSLog

在PCH文件里面使用這個,然后就可以使用SLLog來代替NSLog
/*** 日志 ***/
#ifdef DEBUG
#define SLLog(...) NSLog(__VA_ARGS__)
#else
#define SLLog(...)
#endif
其實這個意思就是如果在調(diào)試階段我們就使用SLLog來代替NSLog 如果在發(fā)布階段,SLLog 就用空來代替,意思是沒有使用打印調(diào)試

剛才寫到了一個DEBUG 這個宏 這里突然又想和大家分享一點宏的知識,我們在定義宏時候,是可以訪問到宏的


Untitle.gif
但是有時候,卻發(fā)現(xiàn)一些訪問不到,比如下面這樣,然后你可能找了很久

也找不多。


Untitlef.gif
其實要這樣找才能找得到
Snip20160822_12.png

4.PCH的一個注意細節(jié)

#ifndef PrefixHeader_pch
#define PrefixHeader_pch

/*** 如果希望某些內(nèi)容能拷貝到任何源代碼文件(OC\C\C++等), 那么就不要寫在
#ifdef __OBJC__和#endif之間 ***/


/***** 在#ifdef __OBJC__和#endif之間的內(nèi)容, 只會拷貝到OC源代碼文件中, 不會拷貝到其他語言的源代碼文件中 *****/
#ifdef __OBJC__


#endif
/***** 在#ifdef __OBJC__和#endif之間的內(nèi)容, 只會拷貝到OC源代碼文件中, 不會拷貝到其他語言的源代碼文件中 *****/


#endif

/*** 如果希望某些內(nèi)容能拷貝到任何源代碼文件(OC\C\C++等), 那么就不要寫在#ifdef OBJC和#endif之間,如果寫在了里面的話會報下面這個錯誤 ***/

Snip20151105_8.png

5.顏色相關(guān)的宏

剛才小編給大家寫那個宏的時候,寫著寫著就想多寫一些其他東西,這個給大家寫一下顏色相關(guān)的宏


/*** 顏色 ***/
#define SLColor(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a/255.0]

/*** RGB顏色 ***/
#define KRGB(r, g, b) SLColor((r), (g), (b), 255)
//整個項目背景顏色
#define ALLbackGroundColor KRGB(221, 226, 229)
/*** 隨機顏色 ***/
#define RandomColor KRGB(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))
這里注意需要先寫第一個,不讓后面的宏就調(diào)用不到上面的第一個宏,因為順序是由上到下來讀的。注意這面的r g b 添加()的作用是為了嚴謹性,有時候?qū)懙?23 + 54這樣就會存在邏輯運算符的順序的問題,所以在定義宏的時候,給加上()

6.將數(shù)據(jù)寫成Plist

來看一下基本的方法

這是接口:http://192.168.2.226:8090/api/financeapp/finance/getBids 

需要拼接的參數(shù)
pageId=1
pageSize=20
所以我們會把接口和參數(shù)一塊拼接起來變成這樣
http://192.168.2.226:8090/api/financeapp/finance/getBids/pageId=1/pageSize=20
然后放到goole瀏覽器,當然前提是瀏覽器裝了插件
Snip20160822_16.png
當然這樣去查看解析的數(shù)據(jù)也是不錯的,只不過要一步一步拼接參數(shù)有點麻煩

下面告訴大家其實也可以用代碼實現(xiàn),直接生成一個plist文件在桌面

Snip20160822_17.png

然后將桌面的plist文件點開就是這樣

Snip20160822_18.png

生成這個文件之后把剛才寫的代碼刪除(避免重復(fù)創(chuàng)建)當然您喜歡也可以寫成宏放到PCH文件里面,這里告訴大家怎么定義成宏,然后使用起來方便

Snip20160822_21.png

寫成宏之后的使用

Snip20160822_24.png

7.UITableViewcell的背景色的設(shè)置

我們不應(yīng)該直接使用cell.backgroundColor。Cell本身是一個UIView,我們所看到的部分其實只是它的一個Subview,也就是cell.contentView。所以,如果直接改變cell本身的背景色,依然會被cell.contentView給覆蓋,沒有效果。 所以,最好的方式應(yīng)該是通過cell.backgroundView來改變cell的背景。按照文檔說明,backgroundView始終處于cell的最下層,所以,將cell里的其它subview背景設(shè)為[UIColor clearColor],以cell.backgroundView作為統(tǒng)一的背景,應(yīng)該是最好的方式。

  UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor redColor];
        cell.backgroundView = view;

但是小編在Xcode7.3的時候,試了一下,好像可以直接設(shè)置cell.backgroundColor也有用,其實在Xcode5之前是必須要這樣設(shè)置的

8.僅僅只隱藏第一級導(dǎo)航欄,這個基礎(chǔ)上,第二級的導(dǎo)航欄不要隱藏

Untitle.gif
- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [super viewWillDisappear:animated];
}

9.修改狀態(tài)欄為白色

在iOS9.0之前要通過這樣設(shè)置


CBD985D7-5BB2-46EC-BE9A-1193EAEC5D47.png

然后在AppDelegate.m中加上一句代碼


5B702A76-BA11-4288-87A7-BD167C4097E0.png

這里會警告是因為我這里是iOS9.3了.估計在iOS10之后這個方法就廢棄了,
但是很值得注意的是如果你使用點語法卻不會出現(xiàn)警告
Snip20160823_11.png

然后在AppDelegate.m中加上一句代碼


Snip20160823_10.png

現(xiàn)在是使用的是這個方法

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

10.啟動頁面時候,狀態(tài)欄隱藏

只需要在info.plist中設(shè)置一下就可以了,同時,別忘記了在AppDelegate.m中加一句代碼

第一步:


Snip20160823_14.png

第二步:


Snip20160823_17.png

11.修改UILable的某部分字顏色

- (void)touchesEnded:(NSSet<UITouch> *)touches withEvent:(UIEvent *)event
{
    [self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]];
}
 
- (void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color {
    // string為整體字符串, editStr為需要修改的字符串
    NSRange range = [string rangeOfString:editStr];
 
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string];
 
    // 設(shè)置屬性修改字體顏色UIColor與大小UIFont
    [attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range];
 
    self.label.attributedText = attribute;
}

12.調(diào)整UITableView的那個分割線位置

tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);

13.導(dǎo)航欄隨著滑動時候就隱藏顯示

 self.navigationController.hidesBarsOnSwipe = YES;

效果圖


Untitle.gif
上面導(dǎo)航欄隨著滑動就隱藏的方法。我們也可以自己通過代碼實現(xiàn)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y + _tableView.contentInset.top;
    CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.tableView].y;
    if (offsetY > 64) {
        if (panTranslationY > 0)
        {
            //下滑趨勢,顯示
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        } else {
            //上滑趨勢,隱藏
            [self.navigationController setNavigationBarHidden:YES animated:YES];
        }
    } else {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}

效果圖


Untitle.gif

14.解決UITableViewcell分割線短了一小段的問題

默認情況是樣的


Snip20160824_1.png

在控制器中加上下面這段代碼

-(void)viewDidLayoutSubviews{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero]; 
    }
}
Snip20160824_2.png

15.UITableView的索引背景色

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {      
  
  for(UIView *view in [tv subviews])  
  {  
    if([[[view class] description] isEqualToString:@"UITableViewIndex"])  
    {  
  
      [view setBackgroundColor:[UIColor whiteColor]];  
      [view setFont:[UIFont systemFontOfSize:14]];  
    }  
  }  
  
  //rest of cellForRow handling...  
  
}  

16:修改了系統(tǒng)自帶頭文件后,Xcode會報錯,需要清除緩存

/Users/電腦名的用戶名/資源庫/Developer/Xcode/DerivedData
例如:/Users/kevindemac/Library/Developer/Xcode/DerivedData
這里要注意kevindemac就是Finder里面的個人
來到這個文件夾下:刪除文件夾的緩存就??

17:計算文字的寬度

    NSString *string = @"哇哈哈";
    CGFloat stringWidth = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}].width;
    NSLog(@"%f",stringWidth);
總結(jié):CGFloat titleW = [字符串 sizeWithAttributes:@{NSFontAttributeName : 字體大小}].width;

18:文字內(nèi)容換行

- 如何讓storyboard\xib中的文字內(nèi)容換行
    - 快捷鍵: option + 回車鍵:也就是你鍵盤上的Ctrl
    - 在storyboard\xib輸入\n是無法實現(xiàn)換行的
- 在代碼中輸入\n是可以實現(xiàn)換行的

19:有透明度的顏色

[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];

20:解決tableView出現(xiàn)多余行的問題

比如出現(xiàn)這種情況:

  self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

21:UIimageView的創(chuàng)建問題

//第一種創(chuàng)建方式:圖片本身是多大創(chuàng)建出來的圖片就是多大
  UIImageView *image1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"friendTrends_icon"]];
    image1.center = CGPointMake(100, 100);
    [self.view addSubview:image1];
 //第二種創(chuàng)建方式:給定圖片尺寸是多大創(chuàng)建出來就是多大,這樣圖片就可能會拉伸
    UIImageView *image2 = [[UIImageView alloc] init];
    image2.frame = CGRectMake(100, 100, 30, 30);
    image2.image = [UIImage imageNamed:@"friendTrends_icon"];
    [self.view addSubview:image2];

22:按鈕大小和圖片大小一致( 這個前提是自己添加了那個分類才可以直接拿到size)

   btn.LYW_size = [UIImage imageNamed:@"MainTagSubIcon"].size;
   btn.LYW_size = [btn imageForState:UIControlStateNormal].size;
   btn.LYW_size = btn.currentImage.size;
   [btn sizeToFit];

23:json 字符串

我們在使用post時候不一定就是簡單的字典,比如這種就是json字符串

{
    "token": "0831E5A2E4734AFDB90972CC0E0AEE83" ,
    "authItemInfo":{
                    "itemId": "17",////認證項目
                            //********手機認證      
                    "cellNumber": "18620300073", //手機號
                    "cellPassword": "831104",//服務(wù)密碼
                            //京東認證
                    "jdAccount": " jdAccount",//京東賬號
                    "jdPassword": "jdPassword", //京東密碼
                    "captcha": "captcha",//網(wǎng)站短信驗證碼(根據(jù)流程碼process_code動態(tài)輸入)
                    "queryPwd": "queryPwd", //查詢密碼(僅北京移動會出現(xiàn),官網(wǎng)的客服密碼,根據(jù)流程碼process_code動態(tài)輸入)
                                        //******學歷認證
                    "chsiAccount": " chsiAccount",//學信網(wǎng)賬號
                    "chsiPassword": "chsiPassword",//學信網(wǎng)密碼
                                    //****身份證,工作證明
                    "authFiles": [
                        {
                            "fileType": 1,
                            "fileName": "/data/uploads/cert/2016/07/21/15/97de1236421531f37ceed4a4b1767b5c.jpg"
                        },
                        {
                            "fileType": 1,
                            "fileName": "/data/uploads/cert/2016/07/21/15/eb41c0c14ae28bc76a34b823fe6dc962.jpg"
                        },
                        {
                            "fileType": 1,
                            "fileName": "/data/uploads/cert/2016/07/21/15/e9e85f991d6fc24743147b7e45f37035.jpg"
                        }
                    ]
                }
            }   

需要這樣轉(zhuǎn)換后上傳

 NSString *url = [NSString stringWithFormat:@"%@/saveAuthItem",SDLOAN_URL];
        NSDictionary *dictPlace =@{@"itemId":@"7",
                                   @"authFiles":@[                                           @{@"fileName":_aliIDCardOne,@"fileType":@"1",@"position":@(1)},
                                     @{@"fileName":_aliIDCardTwo,@"fileType":@"1",@"position":@(2)}]};
    NSError *errors;
        NSData *jsonDatas = [NSJSONSerialization dataWithJSONObject:dictPlace options:NSJSONWritingPrettyPrinted error:&errors];
        NSString *jsonStrings = [[NSString alloc] initWithData:jsonDatas encoding:NSUTF8StringEncoding];
        NSDictionary *params = @{@"token":Token,@"authItemInfo":jsonStrings};

或者如果導(dǎo)入了MJExtension的話,可以這樣轉(zhuǎn)

NSString *json = dictPlace.mj_JSONString;

另外自己可以寫兩個方法去轉(zhuǎn)JSON字符串


//數(shù)組轉(zhuǎn)JSON字符串
+ (NSString *)arrayToJSONString:(NSArray *)array
{
   NSError *error = nil;
   //    NSMutableArray *muArray = [NSMutableArray array];
   //    for (NSString *userId in array) {
   //        [muArray addObject:[NSString stringWithFormat:@"\"%@\"", userId]];
   //    }
   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
   NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   //    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
   //    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
   //    NSLog(@"json array is: %@", jsonResult);
   return jsonString;
}

//字典轉(zhuǎn)JSON字符串
+ (NSString *)dictionaryToJSONString:(NSDictionary *)dictionary
{
   NSError *error = nil;
   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
   NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   //    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
   //    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
   return jsonString;
}


24:復(fù)制

UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
    pasteBoard.string = @"1234567890";

25.TableView的自適應(yīng)高度

#注意,這兩行代碼是TableView的自適應(yīng)高度
        _tableView.estimatedRowHeight = 100;
        _tableView.rowHeight = UITableViewAutomaticDimension;

26:

一個#號在宏中的定義是“ ”雙引號
兩個#號的意思是拼接

27:

CFBundleShortVersionString 標識應(yīng)用程序的發(fā)布版本號。這個版本號是由三個時期分割的整數(shù)組成的字符串。第一個整數(shù)代表重大修改的版本,例如實現(xiàn)新的功能或重大變化的修訂;第二個整數(shù)表示修訂,實現(xiàn)較突出的特點;第三個整數(shù)代表維護版本。該鍵的值不同于“CFBundleVersion”標識。

CFBundleVersion 標識內(nèi)部版本號,可以是發(fā)布了的,也可以是還未發(fā)布的。這是一個單調(diào)增加的字符串,包括一個或多個時期分隔的整數(shù)。

28:調(diào)整UILable行間距

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:label.text];    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:20];
    [attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, label.text.length)];    label.attributedText = attrString;

28:調(diào)用調(diào)用UIImagePickerController顯示中文英文的問題

調(diào)用UIImagePickerController.png

29:圖片和字符串之間的轉(zhuǎn)換

//圖片轉(zhuǎn)字符串
+ (NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 5.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

//字符串轉(zhuǎn)圖片
+ (UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
    NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:_encodedImageStr];
    UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
    return _decodedImage;
}

類似安卓提示消息

+ (void)showMessage:(NSString *)message
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(320, 9000)];
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    showview.frame = CGRectMake((LYWScreenWidth - LabelSize.width - 20)/2, LYWScreenHeight - 100, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:3 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}

判斷字符串為空

+ (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;
}

檢測代碼量

用命令行 先進入cd 項目 再輸入以下代碼

find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.h" -or -name "*.rss" ")" -print | xargs wc -l

或者使用GitHub 上別人寫的一個東西

https://github.com/976971956/DEMOlineNUM

改變 UITextField 占位文字 顏色

[_userName setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

禁止橫屏 在Appdelegate 使用

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window  
{  
    return UIInterfaceOrientationMaskPortrait;  
}

修改狀態(tài)欄顏色 (默認黑色,修改為白色)

1.在Info.plist中設(shè)置

UIViewControllerBasedStatusBarAppearance 為NO

在需要改變狀態(tài)欄顏色的 AppDelegate中在 didFinishLaunchingWithOptions 方法中增加:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

如果需要在單個ViewController中添加,在ViewDidLoad方法中增加:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

模糊效果

    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *test = [[UIVisualEffectView alloc] initWithEffect:effect];
    test.frame = self.view.bounds;
    test.alpha = 0.5;
    [self.view addSubview:test];

前往設(shè)置

 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

系統(tǒng)的分享

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[@"1",@"2",@"3"] applicationActivities:nil];
    activityVC.view.backgroundColor = [UIColor clearColor];
    activityVC.excludedActivityTypes = @[UIActivityTypePrint,UIActivityTypeAssignToContact,UIActivityTypeAddToReadingList,UIActivityTypeAirDrop];
    
    [self presentViewController:activityVC animated:YES completion:nil];

抓包

http://www.itdecent.cn/p/5539599c7a25

手機運營商


-(void)getcarrierName{
    CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
    NSString *currentCountry=[carrier carrierName];
    NSLog(@"[carrier isoCountryCode]==%@,[carrier allowsVOIP]=%d,[carrier mobileCountryCode=%@,[carrier mobileCountryCode]=%@",[carrier isoCountryCode],[carrier allowsVOIP],[carrier mobileCountryCode],[carrier mobileNetworkCode]);
    NSLog(@"運營商:%@",currentCountry);
}

url中帶中文

// UIWebView加載不出后臺返回的url地址。是因為url中帶有中文的原因,需要解碼。
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedString = [self.url stringByAddingPercentEncodingWithAllowedCharacters:set];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:encodedString]]];

 1.獲取identifierForVendor標示手機
    NSString *identifierForVendor = [[UIDevice currentDevice].identifierForVendor UUIDString];
http://blog.csdn.net/u014220518/article/details/50509559
Xcode編譯報錯: 
This application’s application-identifier entitlement does not match that of the installed application. These values must match for an upgrade to be allowed.

原因:兩次編譯的用的證書不一致。

數(shù)組去除相同元素

  NSArray *dataArray = @[@"1",@"1",@"2",@"3",@"4",@"1"];
    
    NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:dataArray.count];
    // 外層一個循環(huán)
    for (NSString *item in dataArray) {
        // 調(diào)用-containsObject:本質(zhì)也是要循環(huán)去判斷,因此本質(zhì)上是雙層遍歷
        // 時間復(fù)雜度為O ( n^2 )而不是O (n)
        if (![resultArray containsObject:item]) {
            [resultArray addObject:item];
        }
    }
    NSLog(@"resultArray: %@", resultArray);

數(shù)組的四種遍歷方式

    /// 以數(shù)組為例 實現(xiàn)下面4種遍歷
    NSArray *array = @[@"1", @"2", @"3"];
    
    /// 遍歷方式1 常規(guī)for循環(huán)
    for (NSInteger i = 0; i < [array count]; i++) {
        NSLog(@"%@", array[I]);
    }
    
    /// 遍歷方式2 Objective-C 1.0 的NSEnumerator
    NSEnumerator *enu = [array objectEnumerator];
    id next = nil;
    while ((next = enu.nextObject) != nil) {
        // 當next為nil時 遍歷結(jié)束
        NSLog(@"%@", next);
    }
    
    /// 遍歷方式3 Objective-C 2.0 引入的for-in
    for (id obj in array) {
        NSLog(@"%@", obj);
    }
    
    /// 遍歷方式4 最新的塊遍歷
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        // stop為YES時 結(jié)束遍歷
        if (*stop == NO) {
            NSLog(@"%@", obj);
        }
    }];

cell的點擊顏色

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
//        [self setupView];
        [self setupCustomCellSelectedColor];
    }
    return self;
    
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    [self setupCustomCellSelectedColor];

}
調(diào)用該方法
- (void)setupCustomCellSelectedColor
{
    CGRect rect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //高亮顏色值
    UIColor *selectedColor = [UIColor redColor];
    CGContextSetFillColorWithColor(context, [selectedColor CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.selectedBackgroundView = [[UIImageView alloc] initWithImage:image];
}

[iOS 11 UIScrollView的新特性(automaticallyAdjustsScrollViewInsets 不起作用了)]

解決方法

    if (@available(iOS 11.0, *)) {
        
        _scroll.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = NO;

    }

swift自定義Log


func LYWLog<T>(_ message:T,file:String = #file,funcName:String = #function,lineNum:Int=#line)  {
    
    let fileName = (file as NSString).lastPathComponent
    
    print("\(fileName):[\(funcName)](\(lineNum)-\(message))")
}

Error returned in reply: Connection invalid

解決方法:把Xcode 以及模擬器全部關(guān)掉 從新啟動一個Xcode就好了
ERROR ITMS-90096: "Your binary is not optimized for iPhone 5 - New iPhone apps and app updates submitted must support the 4-inch display on iPhone 5 and must include a launch image referenced in the Info.plist under UILaunchImages with a UILaunchImageSize value set to {320, 568}. Launch images must be PNG files and located at the top-level of your bundle, or provided within each .lproj folder if you localize your launch images. Learn more about iPhone 5 support and app launch images by reviewing the 'iOS Human Interface Guidelines' at https://developer.apple.com/ios/human-interface-guidelines/graphics/launch-screen."

特么的要是遇到這個問題,別特么聽網(wǎng)上一大堆的解決方案,說白了就是你的啟動圖片不對。要么啟動圖片的尺寸不對,要么就是圖片中不是png的圖片。

關(guān)于移動硬盤無法修改資料的問題

http://www.pc6.com/mac/117369.html

圖片設(shè)置圓角

//cornerRadius 設(shè)置為self.iconImage圖片寬度的一半(圓形圖片)

    self.iconImage.layer.cornerRadius = 20;
    self.iconImage.layer.masksToBounds = YES;

在此之后建議大家盡量不要這么設(shè)置, 因為使用圖層過量會有卡頓現(xiàn)象, 特別是弄圓角或者陰影會很卡, 如果設(shè)置圖片圓角我們一般用繪圖來做:

- (UIImage *)cutCircleImage {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 獲取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 設(shè)置圓形
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
    CGContextClip(ctr);
    // 將圖片畫上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

UILable修改行距

1.UILabel修改文字行距,首行縮進
lineSpacing: 行間距
firstLineHeadIndent:首行縮進
font: 字體
textColor: 字體顏色
- (NSDictionary *)settingAttributesWithLineSpacing:(CGFloat)lineSpacing FirstLineHeadIndent:(CGFloat)firstLineHeadIndent Font:(UIFont *)font TextColor:(UIColor *)textColor{
    //分段樣式
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    //行間距
    paragraphStyle.lineSpacing = lineSpacing;
    //首行縮進
    paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;
    //富文本樣式
    NSDictionary *attributeDic = @{
                                   NSFontAttributeName : font,
                                   NSParagraphStyleAttributeName : paragraphStyle,
                                   NSForegroundColorAttributeName : textColor
                                   };
    return attributeDic;
}

判斷是否為gif/png圖片的正確姿勢

//假設(shè)這是一個網(wǎng)絡(luò)獲取的URL
   NSString *path = @"http://pic3.nipic.com/20090709/2893198_075124038_2.gif";
   // 判斷是否為gif
   NSString *extensionName = path.pathExtension;
    if ([extensionName.lowercaseString isEqualToString:@"gif"]) {
        //是gif圖片
    } else {
        //不是gif圖片
    }

以上判斷看似是可以的,但是這不嚴謹?shù)? 在不知道圖片擴展名的情況下, 如何知道圖片的真實類型 ? 其實就是取出圖片數(shù)據(jù)的第一個字節(jié), 就可以判斷出圖片的真實類型那該怎么做呢如下:

//通過圖片Data數(shù)據(jù)第一個字節(jié) 來獲取圖片擴展名
- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";     
        case 0x47:
            return @"gif";        
        case 0x49:   
        case 0x4D:
            return @"tiff";        
        case 0x52:  
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}

使用 IQKeyboardManager如果你的視圖有導(dǎo)航欄,你不想上移View時,UINavigationBar消失,你也可以進行相應(yīng)設(shè)置:

如果你使用的是代碼,你就需要覆蓋UIViewController中的'-(void)loadView' 方法:
##添加額外代碼,避免導(dǎo)航欄
  UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.scrollEnabled = YES;
    [self.view addSubview:scrollView];
  #scroll.scrollEnabled = NO

如果你使用的是storyboard or xib,只需將當前視圖視圖控制器中的UIView class變?yōu)閁IScrollView。
image.png

備注:

如果有不足或者錯誤的地方還望各位讀者批評指正,可以評論留言,筆者收到后第一時間回復(fù)。

QQ/微信:2366889552 /lan2018yingwei。

簡書號:凡塵一笑:[簡書]

http://www.itdecent.cn/users/0158007b8d17/latest_articles

感謝各位觀眾老爺?shù)拈喿x,如果覺得筆者寫的還湊合,可以關(guān)注或收藏一下,不定期分享一些好玩的實用的demo給大家。

文/凡塵一笑(簡書作者)

原文鏈接: http://www.itdecent.cn/p/8ae080edb3ea

著作權(quán)歸作者所有,轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),并標注“簡書作者”。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容