<track id="rffo1"><div id="rffo1"></div></track>
        <track id="rffo1"><div id="rffo1"></div></track>

            <nobr id="rffo1"><optgroup id="rffo1"></optgroup></nobr>

            亦強科技 > 開發資訊 > iOS實戰技巧

            iOS實戰技巧


            2016年01月27日 79 Yimouleng 分類:開發資訊

            這是我在網上搜索到的iOS高級開發實戰講解,由于原文不是很方便瀏覽,所以我在這里整理一部分出來,方便查閱,同時謝謝原作者。

            這里我不是每一個都收錄進來,這里只是放出一部分,有些用的太多,我就沒整理了,大家如果想看可以去看原文。

            根據顏色生成一張尺寸為1*1的相同顏色圖片



            + (UIImage *)imageWithColor:(UIColor *)color
            {
                // 描述矩形
                CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
            
                // 開啟位圖上下文
                UIGraphicsBeginImageContext(rect.size);
                // 獲取位圖上下文
                CGContextRef context = UIGraphicsGetCurrentContext();
                // 使用color演示填充上下文
                CGContextSetFillColorWithColor(context, [color CGColor]);
                // 渲染上下文
                CGContextFillRect(context, rect);
                // 從上下文中獲取圖片
                UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
                // 結束上下文
                UIGraphicsEndImageContext();
            
                return theImage;
            }


            返回輸入鍵盤



            - (BOOL)textFieldShouldReturn:(UITextField *)textField {
                [textField resignFirstResponder];
                return YES;
            }


            點擊屏幕收回鍵盤



            - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
            {
                [self.view endEditing:YES];
            }


            CGRect



            CGRectFromString(<#NSString *string#>)//有字符串恢復出矩形
            CGRectInset(<#CGRect rect#>, <#CGFloat dx#>, <#CGFloat dy#>)//創建較小或者較大的矩形
            CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>)//判斷兩巨星是否交叉,是否重疊
            CGRectZero//高度和寬度為零的,位于(0,0)的矩形常量


            隱藏狀態欄



            [UIApplication sharedApplication] setStatusBarHidden:<#(BOOL)#> withAnimation:<#(UIStatusBarAnimation)#>//隱藏狀態欄


            自動適應父視圖大小



            self.view.autoresizesSubviews = YES;
                self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;


            UITableView的一些方法



            這里我自己做了個測試,縮進級別設置為行號,row越大,縮進越多- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
                NSInteger row = indexPath.row;
                return row;
            }


            把plist文件中的數據賦給數組



            NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];
            NSArray *array = [NSArray arrayWithContentsOfFile:path];


            獲取觸摸的點



            - (CGPoint)locationInView:(UIView *)view;
            - (CGPoint)previousLocationInView:(UIView *)view;


            獲取觸摸的屬性



            @property(nonatomic,readonly) NSTimeInterval      timestamp;
            @property(nonatomic,readonly) UITouchPhase        phase;
            @property(nonatomic,readonly) NSUInteger          tapCount;


            從plist中獲取數據賦給字典



            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"plist"];
            NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];


            NSUserDefaults注意事項



            設置完了以后如果存儲的東西比較重要的話,一定要同步一下
            [[NSUserDefaults standardUserDefaults] synchronize];


            獲取Documents目錄



            NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];


            獲取tmp目錄



            NSString *tmpPath = NSTemporaryDirectory();


            利用Safari打開一個鏈接



            NSURL *url = [NSURL URLWithString:@"http://baidu.com"];
            [[UIApplication sharedApplication] openURL:url];


            利用UIWebView顯示pdf文件,網頁等等



            UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
            webView.delegate = self;
            webView.scalesPageToFit = YES;
            webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            [webView setAllowsInlineMediaPlayback:YES];
            [self.view addSubview:webView];
                
            NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"pdf"];
            NSURL *url = [NSURL fileURLWithPath:pdfPath];
            NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:5];
            [webView loadRequest:request];


            UIWebView和html的簡單交互



            myWebView = [[UIWebView alloc]initWithFrame:self.view.bounds];
            [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
            NSError *error;
            NSString *errorString = [NSString stringWithFormat:@"",error];
            [myWebView loadHTMLString:errorString baseURL:nil];
            
            //頁面跳轉了以后,停止載入
            -(void)viewWillDisappear:(BOOL)animated {
                if (myWebView.isLoading) {
                    [myWebView stopLoading];
                }
                myWebView.delegate = nil;
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            }


            漢字轉碼



            NSString *oriString = @"\u67aa\u738b";
            NSString *escapedString = [oriString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


            處理鍵盤通知



            先注冊通知,然后實現具體當鍵盤彈出來要做什么,鍵盤收起來要做什么
            - (void)registerForKeyboardNotifications {
                keyboardShown = NO;//標記當前鍵盤是沒有顯示的
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
            }
            //鍵盤顯示要做什么
            - (void)keyboardWasShown:(NSNotification *)notification {
                if (keyboardShown) {
                    return;
                }
                NSDictionary *info = [notification userInfo];
                
                NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
                CGSize keyboardSize = [aValue CGRectValue].size;
                CGRect viewFrame = scrollView.frame;
                viewFrame.size.height = keyboardSize.height;
                
                CGRect textFieldRect = activeField.frame;
                [scrollView scrollRectToVisible:textFieldRect animated:YES];
                keyboardShown = YES;
            }
            
            - (void)keyboardWasHidden:(NSNotification *)notification {
                NSDictionary *info = [notification userInfo];
                NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
                CGSize keyboardSize = [aValue CGRectValue].size;
                
                CGRect viewFrame = scrollView.frame;
                viewFrame.size.height += keyboardSize.height;
                scrollView.frame = viewFrame;
                
                keyboardShown = NO;
            }


            點擊鍵盤的next按鈕,在不同的textField之間換行



            - (BOOL)textFieldShouldReturn:(UITextField *)textField {
                
                if ([textField returnKeyType] != UIReturnKeyDone) {
                    NSInteger nextTag = [textField tag] + 1;
                    UIView *nextTextField = [self.tableView viewWithTag:nextTag];
                    [nextTextField becomeFirstResponder];
                }else {
                    [textField resignFirstResponder];
                }
                
                return YES;
            }


            設置日期格式



            dateFormatter = [[NSDateFormatter alloc]init];
            dateFormatter.locale = [NSLocale currentLocale];
            dateFormatter.calendar = [NSCalendar autoupdatingCurrentCalendar];
            dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
            dateFormatter.dateStyle = NSDateFormatterShortStyle;
            NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);


            加載大量圖片的時候,可以使用



            NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];
            UIImage *myImage = [UIImage imageWithContentsOfFile:imagePath];


            有時候在iPhone游戲中,既要播放背景音樂,同時又要播放比如槍的開火音效。



            NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"xx" ofType:@"wav"];
            NSURL *musicURL = [NSURL fileURLWithPath:musicFilePath];
            AVAudioPlayer *musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:musicURL error:nil];
            [musicPlayer prepareToPlay];
            musicPlayer.volume = 1;
            musicPlayer.numberOfLoops = -1;//-1表示一直循環


            從通訊錄中讀取電話號碼,去掉數字之間的-



            NSString *originalString = @"(123)123123abc";
            NSMutableString *strippedString = [NSMutableString stringWithCapacity:originalString.length];
            NSScanner *scanner = [NSScanner scannerWithString:originalString];
            NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
            
                while ([scanner isAtEnd] == NO) {
                    NSString *buffer;
                    if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
                        [strippedString appendString:buffer];
                    }else {
                        scanner.scanLocation = [scanner scanLocation] + 1;
                    }
                }
                NSLog(@"%@",strippedString);


            正則判斷:字符串只包含字母和數字



            NSString *myString = @"Letter1234";
            NSString *regex = @"[a-z][A-Z][0-9]";
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
            
                if ([predicate evaluateWithObject:myString]) {
                    //implement
                }


            設置UITableView的滾動條顏色



            self.tableView.indicatorStyle = UIScrollViewIndicatorStyleWhite;


            網絡編程

            開發web等網絡應用程序的時候,需要確認網絡環境,連接情況等信息。如果沒有處理它們,是不會通過apple的審查的。
            系統自帶的網絡檢查是原生的,AFNetworking也為我們添加了相關檢測機制,所以這個直接在介紹AFNetworking的時候詳解吧。

            使用NSURLConnection下載數據



            1. 創建對象
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
            [NSURLConnection connectionWithRequest:request delegate:self];
            
            2. NSURLConnection delegate 委托方法
            - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
            
            }
            
            - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
                
            }
            
            - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
                
            }
            
            - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
                
            }
            
            3. 實現委托方法
            - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
                self.receiveData.length = 0;//先清空數據
            }
            
            - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
                [self.receiveData appendData:data];
            }
            
            - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
                //錯誤處理
            }
            
            - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                NSString *returnString = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];
                firstTimeDownloaded = YES;
            }


            iOS的動畫以及自定義圖形,開個專欄總結。

            隱藏狀態欄



            [UIApplication sharedApplication].statusBarHidden = YES;


            .m文件與.mm文件的區別



            .m文件是objective-c文件
            .mm文件相當于c++或者c文件


            Safari其實沒有把內存的緩存寫到存儲卡上

            讀取一般性文件



            - (void)readFromTXT {
                NSString *tmp;
                NSArray *lines;//將文件轉化為一行一行的
                lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"] componentsSeparatedByString:@"\n"];
                
                NSEnumerator *nse = [lines objectEnumerator];
                
                //讀取<>里的內容
                while (tmp == [nse nextObject]) {
                    NSString *stringBetweenBrackets = nil;
                    NSScanner *scanner = [NSScanner scannerWithString:tmp];
                    [scanner scanUpToString:@"<" intoString:nil];
                    [scanner scanString:@"<" intoString:nil];
                    [scanner scanUpToString:@">" intoString:&stringBetweenBrackets];
                    NSLog(@"%@",[stringBetweenBrackets description]);
                }
            }

             [self.navigationController setNavigationBarHidden:YES animated:YES];


            調用電話,短信,郵件



            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto:apple@mac.com?Subject=hello"]];
            sms://調用短信
            tel://調用電話
            itms://打開MobileStore.app


            獲取版本信息



            UIDevice *myDevice = [UIDevice currentDevice];
            NSString *systemVersion = myDevice.systemVersion;


            UIWebView的使用



            webView.delegate = self;
            
            (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
                NSURL *url = request.URL;
                NSString *urlStirng = url.absoluteString;
                NSLog(@"%@",urlStirng);
                return YES;
            }


            UIButtontitleimage不能同時顯示
            UINavigationItem也是

            不要再語言包里面設置空格

            NSNotificationCenter帶參數發送



            MPMoviePlayerController *theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:moviePath]];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];
            [theMovie play];
            
            - (void)myMovieFinishedCallback:(NSNotification *)aNotification {
                MPMoviePlayerController *theMovie = [aNotification object];
                [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];
            }


            延遲一段時間執行某個函數



            [self performSelector:@selector(dismissModal) withObject:self afterDelay:1.0];

            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];


            UIView設置成圓角的方法



            mainView.layer.cornerRadius = 6;
            mainView.layer.masksToBounds = YES;


            Objective-C 內存管理

            1. 一個對象可以有一個或多個擁有者

            2. 當它一個擁有者都沒有的時候,它就會被回收

            3. 如果想保留一個對象不被回收,你就必須成為它的擁有者

            關鍵字

            1. alloc
              為對象分配內存,計數設為1,并返回此對象。

            • copy
              復制一個對象,此對象計數為1,返回此對象。你將成為此克隆對象的擁有者。

            • retain
              對象計數+1,并成為次對象的擁有者。

            • release
              對象計數-1,并丟掉此對象。

            • autorelease
              在未來的某一個時刻,對象計數-1。并在未來的某個時間放棄此對象。

            1. 一個代碼塊內要確保copy,alloc 和 retain 的使用數量與 release 和 autorelease 的數量相等。

            • 在使用以 alloc 或 new 開頭或包含 copy 的方法,或 retain 一個對象時,你將會編程它的擁有者。

            • 實現 dealloc 方法,這是系統當 retain -> 0 的時候,自動調用的。手動調用會引起 retain count 計數錯誤(多一次的 release)。

            iPhone 更改鍵盤右下角按鍵的 type



            SearchBar *mySearchBar = [[UISearchBar alloc]init];
            mySearchBar.frame = CGRectMake(0, 0, self.view.bounds.size.width, 44);
            mySearchBar.placeholder = @"placeholderString";
            mySearchBar.delegate = self;
            [self.view addSubview:mySearchBar];
            UITextField *searchField = [[mySearchBar subviews] lastObject];
            searchField.returnKeyType = UIReturnKeyDone;


          1. 上一篇:設計H5頁面的原因
          2. 下一篇:HTML5簡介
          3. 請將您的寶貴意見發給我們

            Copyright ? 2013-2023 廣州亦強科技有限公司 粵ICP備13085004號

                  <track id="rffo1"><div id="rffo1"></div></track>
                  <track id="rffo1"><div id="rffo1"></div></track>

                      <nobr id="rffo1"><optgroup id="rffo1"></optgroup></nobr>

                      性女传奇在线播放