IOS常用程式碼總結(一)

weixin_34290000發表於2018-03-06

1、設定UILabel行間距

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;

2、當使用-performSelector:withObject:withObject:afterDelay:方法時,需要傳入多引數問題

// 方法一、

// 把引數放進一個陣列/字典,直接把陣列/字典當成一個引數傳過去,具體方法實現的地方再解析這個陣列/字典

NSArray * array =

    [NSArray arrayWithObjects: @"first", @"second", nil];

[self performSelector:@selector(fooFirstInput:) withObject: array afterDelay:15.0];

// 方法二、

// 使用NSInvocation

SEL aSelector = NSSelectorFromString(@"doSoming:argument2:");

    NSInteger argument1 = 10;

    NSString *argument2 = @"argument2";

    if([self respondsToSelector:aSelector]) {

        NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:aSelector]];

        [inv setSelector:aSelector];

        [inv setTarget:self];

        [inv setArgument:&(argument1) atIndex:2];

        [inv setArgument:&(argument2) atIndex:3];

        [inv performSelector:@selector(invoke) withObject:nil afterDelay:15.0];

}

3、UILabel顯示不同顏色字型

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:label.text];

[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];

[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];

[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

label.attributedText = string;

4、比較兩個CGRect/CGSize/CGPoint是否相等

if (CGRectEqualToRect(rect1, rect2)) { // 兩個區域相等

        // do some

    }

    if (CGPointEqualToPoint(point1, point2)) { // 兩個點相等

        // do some

    }

    if (CGSizeEqualToSize(size1, size2)) { // 兩個size相等

        // do some

}

5、比較兩個NSDate相差多少小時

NSDate* date1 = someDate;

NSDate* date2 = someOtherDate;

NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];

double secondsInAnHour = 3600;

// 除以3600是把秒化成小時,除以60得到結果為相差的分鐘數

NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

6、每個cell之間增加間距

// 方法一,每個分割槽只顯示一行cell,分割槽頭當作你想要的間距(注意,從資料來源陣列中取值的時候需要用indexPath.section而不是indexPath.row)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return yourArry.count;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return 1;

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{

    return cellSpacingHeight;

}

// 方法二,在cell的contentView上加個稍微低一點的view,cell上原本的內容放在你的view上,而不是contentView上,這樣能偽造出一個間距來。

// 方法三,自定義cell,重寫setFrame:方法

- (void)setFrame:(CGRect)frame

{

    frame.size.height -= 20;

    [super setFrame:frame];

}

7、播放一張張連續的圖片

// 加入現在有三張圖片分別為animate_1、animate_2、animate_3

// 方法一

    imageView.animationImages = @[[UIImage imageNamed:@"animate_1"], [UIImage imageNamed:@"animate_2"], [UIImage imageNamed:@"animate_3"]];

imageView.animationDuration = 1.0;

// 方法二

    imageView.image = [UIImage animatedImageNamed:@"animate_" duration:1.0];

// 方法二解釋下,這個方法會載入animate_為字首的,後邊0-1024,也就是animate_0、animate_1一直到animate_1024

8、載入gif圖片

推薦使用這個框架FLAnimatedImage

9、防止離屏渲染為image新增圓角

// image分類

- (UIImage *)circleImage

{

// NO代表透明

UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);

// 獲得上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

// 新增一個圓

CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);

// 方形變圓形

CGContextAddEllipseInRect(ctx, rect);

// 裁剪

CGContextClip(ctx);

// 將圖片畫上去

[self drawInRect:rect];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return image;

}

10、檢視系統所有字型

// 列印字型

for (id familyName in [UIFont familyNames]) {

    NSLog(@"%@", familyName);

    for (id fontName in [UIFont fontNamesForFamilyName:familyName]) NSLog(@"  %@", fontName);

}

// 也可以進入這個網址檢視http://iosfonts.com/

11、獲取隨機數

NSInteger i = arc4random();

12、獲取隨機數小數(0-1之間)

#define ARC4RANDOM_MAX      0x100000000

double val = ((double)arc4random() / ARC4RANDOM_MAX);

13、AVPlayer視訊播放完成的通知監聽

[[NSNotificationCenter defaultCenter]

      addObserver:self

      selector:@selector(videoPlayEnd)

      name:AVPlayerItemDidPlayToEndTimeNotification

object:nil];

14、判斷兩個rect是否有交叉

if (CGRectIntersectsRect(rect1, rect2)) {

}

15、判斷一個字串是否為數字

NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

    if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound)

    {

      // 是數字

    } else

    {

      // 不是數字

}

16、將一個view儲存為pdf格式

- (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename

{

    NSMutableData *pdfData = [NSMutableData data];

    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);

    UIGraphicsBeginPDFPage();

    CGContextRef pdfContext = UIGraphicsGetCurrentContext();

    [aView.layer renderInContext:pdfContext];

    UIGraphicsEndPDFContext();

    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];

    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

    [pdfData writeToFile:documentDirectoryFilename atomically:YES];

    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);

}

17、讓一個view在父檢視中心

child.center = [parent convertPoint:parent.center fromView:parent.superview];

18、獲取當前導航控制器下前一個控制器

- (UIViewController *)backViewController

{

    NSInteger myIndex = [self.navigationController.viewControllers indexOfObject:self];

    if ( myIndex != 0 && myIndex != NSNotFound ) {

        return [self.navigationController.viewControllers objectAtIndex:myIndex-1];

    } else {

        return nil;

    }

}

19、儲存UIImage到本地

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

20、鍵盤上方增加工具欄

UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];

[keyboardDoneButtonView sizeToFit];

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"

                                                               style:UIBarButtonItemStyleBordered target:self

                                                              action:@selector(doneClicked:)];

[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];

txtField.inputAccessoryView = keyboardDoneButtonView;

21、copy一個view

因為UIView沒有實現copy協議,因此找不到copyWithZone方法,使用copy的時候導致崩潰

但是我們可以通過歸檔再解檔實現copy,這相當於對檢視進行了一次深拷貝,程式碼如下

id copyOfView =

[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];

22、在image上繪製文字並生成新的image

UIFont *font = [UIFont boldSystemFontOfSize:12];

    UIGraphicsBeginImageContext(image.size);

    [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];

    CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);

    [[UIColor whiteColor] set];

    [text drawInRect:CGRectIntegral(rect) withFont:font];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

23、判斷一個view是否為另一個view的子檢視

// 如果myView是self.view本身,也會返回yes

BOOL isSubView = [myView isDescendantOfView:self.view];

24、判斷一個字串是否包含另一個字串

// 方法一、這種方法只適用於iOS8之後,如果是配iOS8之前用方法二

if ([str containsString:otherStr]) NSLog(@"包含");

// 方法二

NSRange range = [str rangeOfString:otherStr];

if (range.location != NSNotFound) NSLog(@"包含");

25、UICollectionView自動滾動到某行

// 重寫viewDidLayoutSubviews方法

-(void)viewDidLayoutSubviews {

   [super viewDidLayoutSubviews];

   [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];

}

26、修改系統UIAlertController

// 但是據說這種方法會被App Store拒絕(慎用!)

UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];

    NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"我是一個大文字"];

    [hogan addAttribute:NSFontAttributeName

                  value:[UIFont systemFontOfSize:30]

                  range:NSMakeRange(4, 1)];

    [hogan addAttribute:NSForegroundColorAttributeName

                  value:[UIColor redColor]

                  range:NSMakeRange(4, 1)];

    [alertVC setValue:hogan forKey:@"attributedTitle"];

    UIAlertAction *button = [UIAlertAction actionWithTitle:@"Label text" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){ }];

    UIImage *accessoryImage = [UIImage imageNamed:@"1"];

    [button setValue:accessoryImage forKey:@"image"];

    [alertVC addAction:button];

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

27、判斷某一行的cell是否已經顯示

CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];

BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);

28、讓導航控制器pop回指定的控制器

NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];

for (UIViewController *aViewController in allViewControllers) {

    if ([aViewController isKindOfClass:[RequiredViewController class]]) {

        [self.navigationController popToViewController:aViewController animated:NO];

    }

}

29、動畫修改label上的文字

// 方法一

CATransition *animation = [CATransition animation];

    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    animation.type = kCATransitionFade;

    animation.duration = 0.75;

    [self.label.layer addAnimation:animation forKey:@"kCATransitionFade"];

    self.label.text = @"New";

// 方法二

[UIView transitionWithView:self.label

                      duration:0.25f

                       options:UIViewAnimationOptionTransitionCrossDissolve

                    animations:^{

                        self.label.text = @"Well done!";

                    } completion:nil];

// 方法三

[UIView animateWithDuration:1.0

                     animations:^{

                         self.label.alpha = 0.0f;

                         self.label.text = @"newText";

                         self.label.alpha = 1.0f;

}];

30、判斷字典中是否包含某個key值

if ([dic objectForKey:@"yourKey"]) {

    NSLog(@"有這個值");

} else {

    NSLog(@"沒有這個值");

}

31、獲取螢幕方向

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

if(orientation == 0) //Default orientation

    //預設

else if(orientation == UIInterfaceOrientationPortrait)

    //豎屏

else if(orientation == UIInterfaceOrientationLandscapeLeft)

    // 左橫屏

else if(orientation == UIInterfaceOrientationLandscapeRight)

//右橫屏

32、設定UIImage的透明度

// 方法一、新增UIImage分類

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {

    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);

    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

    CGContextSetAlpha(ctx, alpha);

    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

// 方法二、如果沒有奇葩需求,乾脆用UIImageView設定透明度

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"yourImage"]];

imageView.alpha = 0.5;

33、Attempt to mutate immutable object with insertString:atIndex:

這個錯是因為你拿字串呼叫insertString:atIndex:方法的時候,呼叫物件不是NSMutableString,應該先轉成這個型別再呼叫

34、UIWebView新增單擊手勢不響應

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webViewClick)];

        tap.delegate = self;

        [_webView addGestureRecognizer:tap];

// 因為webView本身有一個單擊手勢,所以再新增會造成手勢衝突,從而不響應。需要繫結手勢代理,並實現下邊的代理方法

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{

    return YES;

}

35、獲取手機RAM容量

// 需要匯入#import

mach_port_t host_port;

    mach_msg_type_number_t host_size;

    vm_size_t pagesize;

    host_port = mach_host_self();

    host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);

    host_page_size(host_port, &pagesize);

    vm_statistics_data_t vm_stat;

    if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {

        NSLog(@"Failed to fetch vm statistics");

    }

    /* Stats in bytes */

    natural_t mem_used = (vm_stat.active_count +

                          vm_stat.inactive_count +

                          vm_stat.wire_count) * pagesize;

    natural_t mem_free = vm_stat.free_count * pagesize;

    natural_t mem_total = mem_used + mem_free;

NSLog(@"已用: %u 可用: %u 總共: %u", mem_used, mem_free, mem_total);

36、地圖上兩個點之間的實際距離

// 需要匯入#import

CLLocation *locA = [[CLLocation alloc] initWithLatitude:34 longitude:113];

    CLLocation *locB = [[CLLocation alloc] initWithLatitude:31.05 longitude:121.76];

// CLLocationDistance求出的單位為米

CLLocationDistance distance = [locA distanceFromLocation:locB];

37、在應用中開啟設定的某個介面

// 開啟設定->通用

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];

// 以下是設定其他介面

prefs:root=General&path=About

prefs:root=General&path=ACCESSIBILITY

prefs:root=AIRPLANE_MODE

prefs:root=General&path=AUTOLOCK

prefs:root=General&path=USAGE/CELLULAR_USAGE

prefs:root=Brightness

prefs:root=Bluetooth

prefs:root=General&path=DATE_AND_TIME

prefs:root=FACETIME

prefs:root=General

prefs:root=General&path=Keyboard

prefs:root=CASTLE

prefs:root=CASTLE&path=STORAGE_AND_BACKUP

prefs:root=General&path=INTERNATIONAL

prefs:root=LOCATION_SERVICES

prefs:root=ACCOUNT_SETTINGS

prefs:root=MUSIC

prefs:root=MUSIC&path=EQ

prefs:root=MUSIC&path=VolumeLimit

prefs:root=General&path=Network

prefs:root=NIKE_PLUS_IPOD

prefs:root=NOTES

prefs:root=NOTIFICATIONS_ID

prefs:root=Phone

prefs:root=Photos

prefs:root=General&path=ManagedConfigurationList

prefs:root=General&path=Reset

prefs:root=Sounds&path=Ringtone

prefs:root=Safari

prefs:root=General&path=Assistant

prefs:root=Sounds

prefs:root=General&path=SOFTWARE_UPDATE_LINK

prefs:root=STORE

prefs:root=TWITTER

prefs:root=FACEBOOK

prefs:root=General&path=USAGE prefs:root=VIDEO

prefs:root=General&path=Network/VPN

prefs:root=Wallpaper

prefs:root=WIFI

prefs:root=INTERNET_TETHERING

prefs:root=Phone&path=Blocked

prefs:root=DO_NOT_DISTURB

38、在UITextView中顯示html文字

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 30, 100, 199)];

    textView.backgroundColor = [UIColor redColor];

    [self.view addSubview:textView];

NSString *htmlString = @"

Header

Subheader

Some text

![](http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg)";

    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes: nil error: nil];

textView.attributedText = attributedString;

39、監聽scrollView是否滾動到了頂部/底部

-(void)scrollViewDidScroll: (UIScrollView*)scrollView

{

    float scrollViewHeight = scrollView.frame.size.height;

    float scrollContentSizeHeight = scrollView.contentSize.height;

    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset == 0)

    {

        // 滾動到了頂部

    }

    else if (scrollOffset + scrollViewHeight == scrollContentSizeHeight)

    {

        // 滾動到了底部

    }

}

40、UISlider增量/減量為固定值(假如為5)

- (void)setupSlider

{

    UISlider *slider = [[UISlider alloc] init];

    [self.view addSubview:slider];

    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];

    slider.maximumValue = 100;

    slider.minimumValue = 0;

    slider.frame = CGRectMake(200, 20, 100, 30);

}

- (void)sliderAction:(UISlider *)slider

{

    [slider setValue:((int)((slider.value + 2.5) / 5) * 5) animated:NO];

}

41、選中textField或者textView所有文字(我這裡以textView為例)

[self.textView setSelectedTextRange:[self.textView textRangeFromPosition:self.textView.beginningOfDocument toPosition:self.textView.endOfDocument]]

42、從導航控制器中刪除某個控制器

// 方法一、知道這個控制器所處的導航控制器下標

NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];

[navigationArray removeObjectAtIndex: 2];

self.navigationController.viewControllers = navigationArray;

// 方法二、知道具體是哪個控制器

NSArray* tempVCA = [self.navigationController viewControllers];

for(UIViewController *tempVC in tempVCA)

{

    if([tempVC isKindOfClass:[urViewControllerClass class]])

    {

        [tempVC removeFromParentViewController];

    }

}

43、隱藏UITextView/UITextField游標

textField.tintColor = [UIColor clearColor];

44、當UITextView/UITextField中沒有文字時,禁用Enter鍵

textField.enablesReturnKeyAutomatically = YES;

45、字串encode編碼(編碼url字串不成功的問題)

// 我們一般用這個方法處理stringByAddingPercentEscapesUsingEncoding但是這個方法好想不會處理/和&這種特殊符號,這種情況就需要用下邊這個方法處理

@implementation NSString (NSString_Extended)

- (NSString *)urlencode {

    NSMutableString *output = [NSMutableString string];

    const unsigned char *source = (const unsigned char *)[self UTF8String];

    int sourceLen = strlen((const char *)source);

    for (int i = 0; i < sourceLen; ++i) {

        const unsigned char thisChar = source[i];

        if (thisChar == ' '){

            [output appendString:@"+"];

        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||

                   (thisChar >= 'a' && thisChar <= 'z') ||

                   (thisChar >= 'A' && thisChar <= 'Z') ||

                   (thisChar >= '0' && thisChar <= '9')) {

            [output appendFormat:@"%c", thisChar];

        } else {

            [output appendFormat:@"%%%02X", thisChar];

        }

    }

    return output;

}

46、計算UILabel上某段文字的frame

@implementation UILabel (TextRect)

- (CGRect)boundingRectForCharacterRange:(NSRange)range

{

    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:[self attributedText]];

    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];

    [textStorage addLayoutManager:layoutManager];

    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:[self bounds].size];

    textContainer.lineFragmentPadding = 0;

    [layoutManager addTextContainer:textContainer];

    NSRange glyphRange;

    [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];

    return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];

}

47、獲取隨機UUID

NSString *result;

    if([[[UIDevice currentDevice] systemVersion] floatValue] > 6.0)

    {

       result = [[NSUUID UUID] UUIDString];

    }

    else

    {

        CFUUIDRef uuidRef = CFUUIDCreate(NULL);

        CFStringRef uuid = CFUUIDCreateString(NULL, uuidRef);

        CFRelease(uuidRef);

        result = (__bridge_transfer NSString *)uuid;

}

48、仿蘋果抖動動畫

#define RADIANS(degrees) (((degrees) * M_PI) / 180.0)

- (void)startAnimate {

    view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5));

    [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse) animations:^ {

                         view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5));

                     } completion:nil];

}

- (void)stopAnimate {

    [UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear) animations:^ {

                         view.transform = CGAffineTransformIdentity;

                     } completion:nil];

}

49、修改UISearBar內部背景顏色

UITextField *textField = [_searchBar valueForKey:@"_searchField"];

textField.backgroundColor = [UIColor redColor];

50、UITextView滾動到頂部

    // 方法一

    [self.textView scrollRangeToVisible:NSMakeRange(0, 0)];

    // 方法二

[self.textView setContentOffset:CGPointZero animated:YES];

51、通知監聽APP生命週期

UIApplicationDidEnterBackgroundNotification 應用程式進入後臺

UIApplicationWillEnterForegroundNotification 應用程式將要進入前臺

UIApplicationDidFinishLaunchingNotification 應用程式完成啟動

UIApplicationDidFinishLaunchingNotification 應用程式由掛起變的活躍

UIApplicationWillResignActiveNotification 應用程式掛起(有電話進來或者鎖屏)

UIApplicationDidReceiveMemoryWarningNotification 應用程式收到記憶體警告

UIApplicationDidReceiveMemoryWarningNotification 應用程式終止(後臺殺死、手機關機等)

UIApplicationSignificantTimeChangeNotification 當有重大時間改變(凌晨0點,裝置時間被修改,時區改變等)

UIApplicationWillChangeStatusBarOrientationNotification 裝置方向將要改變

UIApplicationDidChangeStatusBarOrientationNotification 裝置方向改變

UIApplicationWillChangeStatusBarFrameNotification 裝置狀態列frame將要改變

UIApplicationDidChangeStatusBarFrameNotification 裝置狀態列frame改變

UIApplicationBackgroundRefreshStatusDidChangeNotification 應用程式在後臺下載內容的狀態發生變化

UIApplicationProtectedDataWillBecomeUnavailable 本地受保護的檔案被鎖定,無法訪問

UIApplicationProtectedDataWillBecomeUnavailable 本地受保護的檔案可用了

52、觸控事件型別

UIControlEventTouchCancel 取消控制元件當前觸發的事件

UIControlEventTouchDown 點按下去的事件

UIControlEventTouchDownRepeat 重複的觸動事件

UIControlEventTouchDragEnter 手指被拖動到控制元件的邊界的事件

UIControlEventTouchDragExit 一個手指從控制元件內拖到外界的事件

UIControlEventTouchDragInside 手指在控制元件的邊界內拖動的事件

UIControlEventTouchDragOutside 手指在控制元件邊界之外被拖動的事件

UIControlEventTouchUpInside 手指處於控制範圍內的觸控事件

UIControlEventTouchUpOutside 手指超出控制範圍的控制中的觸控事件

53、UITextField文字周圍增加邊距

    // 子類化UITextField,增加insert屬性

@interface WZBTextField : UITextField

@property (nonatomic, assign) UIEdgeInsets insets;

@end

// 在.m檔案重寫下列方法

- (CGRect)textRectForBounds:(CGRect)bounds {

    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {

        return [self adjustRectWithWidthRightView:paddedRect];

    }

    return paddedRect;

}

- (CGRect)placeholderRectForBounds:(CGRect)bounds {

    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {

        return [self adjustRectWithWidthRightView:paddedRect];

    }

    return paddedRect;

}

- (CGRect)editingRectForBounds:(CGRect)bounds {

    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeWhileEditing) {

        return [self adjustRectWithWidthRightView:paddedRect];

    }

    return paddedRect;

}

- (CGRect)adjustRectWithWidthRightView:(CGRect)bounds {

    CGRect paddedRect = bounds;

    paddedRect.size.width -= CGRectGetWidth(self.rightView.frame);

    return paddedRect;

}

54、監聽UISlider拖動狀態

// 新增事件

[slider addTarget:self action:@selector(sliderValurChanged:forEvent:) forControlEvents:UIControlEventValueChanged];

// 實現方法

- (void)sliderValurChanged:(UISlider*)slider forEvent:(UIEvent*)event {

    UITouch *touchEvent = [[event allTouches] anyObject];

    switch (touchEvent.phase) {

        case UITouchPhaseBegan:

            NSLog(@"開始拖動");

            break;

        case UITouchPhaseMoved:

            NSLog(@"正在拖動");

            break;

        case UITouchPhaseEnded:

            NSLog(@"結束拖動");

            break;

        default:

            break;

    }

}

55、設定UITextField游標位置

// textField需要設定的textField,index要設定的游標位置

- (void)cursorLocation:(UITextField *)textField index:(NSInteger)index

{

    NSRange range = NSMakeRange(index, 0);

    UITextPosition *start = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location];

    UITextPosition *end = [textField positionFromPosition:start offset:range.length];

    [textField setSelectedTextRange:[textField textRangeFromPosition:start toPosition:end]];

}

56、去除webView底部黑色

    [webView setBackgroundColor:[UIColor clearColor]];

    [webView setOpaque:NO];

    for (UIView *v1 in [webView subviews])

    {

        if ([v1 isKindOfClass:[UIScrollView class]])

        {

            for (UIView *v2 in v1.subviews)

            {

                if ([v2 isKindOfClass:[UIImageView class]])

                {

                    v2.hidden = YES;

                }

            }

        }

}

57、獲取collectionViewCell在螢幕中的frame

UICollectionViewLayoutAttributes *attributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];

CGRect cellRect = attributes.frame;

CGRect cellFrameInSuperview = [collectionView convertRect:cellRect toView:[cv superview]];

58、比較兩個UIImage是否相等

- (BOOL)image:(UIImage *)image1 isEqualTo:(UIImage *)image2

{

    NSData *data1 = UIImagePNGRepresentation(image1);

    NSData *data2 = UIImagePNGRepresentation(image2);

    return [data1 isEqual:data2];

}

59、解決當UIScrollView上有UIButton的時候,觸控到button滑動不了的問題

// 子類化UIScrollView,並重寫以下方法

- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {

        self.delaysContentTouches = NO;

    }

    return self;

}

- (BOOL)touchesShouldCancelInContentView:(UIView *)view {

    if ([view isKindOfClass:UIButton.class]) {

        return YES;

    }

    return [super touchesShouldCancelInContentView:view];

}

60、UITextView中的文字新增陰影效果

- (void)setTextLayer:(UITextView *)textView color:(UIColor *)color

{

    CALayer *textLayer = ((CALayer *)[textView.layer.sublayers objectAtIndex:0]);

    textLayer.shadowColor = color.CGColor;

    textLayer.shadowOffset = CGSizeMake(0.0f, 1.0f);

    textLayer.shadowOpacity = 1.0f;

    textLayer.shadowRadius = 1.0f;

}

61、MD5加密

+ (NSString *)md5:(NSString *)str

{

    const char *concat_str = [str UTF8String];

    unsigned char result[CC_MD5_DIGEST_LENGTH];

    CC_MD5(concat_str, (unsigned int)strlen(concat_str), result);

    NSMutableString *hash = [NSMutableString string];

    for (int i =0; i <16; i++){

        [hash appendFormat:@"%02X", result[i]];

    }

    return [hash uppercaseString];

}

62、base64加密

@interface NSData (Base64)

/**

*  @brief  字串base64後轉data

*/

+ (NSData *)dataWithBase64EncodedString:(NSString *)string

{

    if (![string length]) return nil;

    NSData *decoded = nil;

#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0

    if (![NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)])

    {

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wdeprecated-declarations"

        decoded = [[self alloc] initWithBase64Encoding:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])]];

#pragma clang diagnostic pop

    }

    else

#endif

    {

        decoded = [[self alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];

    }

    return [decoded length]? decoded: nil;

}

/**

*  @brief  NSData轉string

*  @param wrapWidth 換行長度  76  64

*/

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth

{

    if (![self length]) return nil;

    NSString *encoded = nil;

#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0

    if (![NSData instancesRespondToSelector:@selector(base64EncodedStringWithOptions:)])

    {

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Wdeprecated-declarations"

        encoded = [self base64Encoding];

#pragma clang diagnostic pop

    }

    else

#endif

    {

        switch (wrapWidth)

        {

            case 64:

            {

                return [self base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

            }

            case 76:

            {

                return [self base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];

            }

            default:

            {

                encoded = [self base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];

            }

        }

    }

    if (!wrapWidth || wrapWidth >= [encoded length])

    {

        return encoded;

    }

    wrapWidth = (wrapWidth / 4) * 4;

    NSMutableString *result = [NSMutableString string];

    for (NSUInteger i = 0; i < [encoded length]; i+= wrapWidth)

    {

        if (i + wrapWidth >= [encoded length])

        {

            [result appendString:[encoded substringFromIndex:i]];

            break;

        }

        [result appendString:[encoded substringWithRange:NSMakeRange(i, wrapWidth)]];

        [result appendString:@"\r\n"];

    }

    return result;

}

/**

*  @brief  NSData轉string 換行長度預設64

*/

- (NSString *)base64EncodedString

{

    return [self base64EncodedStringWithWrapWidth:0];

}

63、AES加密

#import

@interface NSData (AES)

/**

*  利用AES加密資料

*/

- (NSData*)encryptedWithAESUsingKey:(NSString*)key andIV:(NSData*)iv {

    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];

    size_t dataMoved;

    NSMutableData *encryptedData = [NSMutableData dataWithLength:self.length + kCCBlockSizeAES128];

    CCCryptorStatus status = CCCrypt(kCCEncrypt,kCCAlgorithmAES128,kCCOptionPKCS7Padding,keyData.bytes,keyData.length,iv.bytes,self.bytes,self.length,encryptedData.mutableBytes, encryptedData.length,&dataMoved);

    if (status == kCCSuccess) {

        encryptedData.length = dataMoved;

        return encryptedData;

    }

    return nil;

}

/**

*  @brief  利用AES解密據

*/

- (NSData*)decryptedWithAESUsingKey:(NSString*)key andIV:(NSData*)iv {

    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];

    size_t dataMoved;

    NSMutableData *decryptedData = [NSMutableData dataWithLength:self.length + kCCBlockSizeAES128];

    CCCryptorStatus result = CCCrypt(kCCDecrypt,kCCAlgorithmAES128,kCCOptionPKCS7Padding,keyData.bytes,keyData.length,iv.bytes,self.bytes,self.length,decryptedData.mutableBytes, decryptedData.length,&dataMoved);

    if (result == kCCSuccess) {

        decryptedData.length = dataMoved;

        return decryptedData;

    }

    return nil;

}

64、3DES加密

#import

@interface NSData (3DES)

/**

*  利用3DES加密資料

*/

- (NSData*)encryptedWith3DESUsingKey:(NSString*)key andIV:(NSData*)iv {

    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];

    size_t dataMoved;

    NSMutableData *encryptedData = [NSMutableData dataWithLength:self.length + kCCBlockSize3DES];

    CCCryptorStatus result = CCCrypt(kCCEncrypt,kCCAlgorithm3DES,kCCOptionPKCS7Padding,keyData.bytes,keyData.length,iv.bytes,self.bytes,self.length,encryptedData.mutableBytes,encryptedData.length,&dataMoved);

    if (result == kCCSuccess) {

        encryptedData.length = dataMoved;

        return encryptedData;

    }

    return nil;

}

/**

*  @brief   利用3DES解密資料

*/

- (NSData*)decryptedWith3DESUsingKey:(NSString*)key andIV:(NSData*)iv {

    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];

    size_t dataMoved;

    NSMutableData *decryptedData = [NSMutableData dataWithLength:self.length + kCCBlockSize3DES];

    CCCryptorStatus result = CCCrypt(kCCDecrypt,kCCAlgorithm3DES,kCCOptionPKCS7Padding,keyData.bytes,keyData.length,iv.bytes,self.bytes,self.length,decryptedData.mutableBytes,decryptedData.length,&dataMoved);

    if (result == kCCSuccess) {

        decryptedData.length = dataMoved;

        return decryptedData;

    }

    return nil;

}

65、單個頁面多個網路請求的情況,需要監聽所有網路請求結束後重新整理UI

dispatch_group_t group = dispatch_group_create();

    dispatch_queue_t serialQueue = dispatch_queue_create("com.wzb.test.www", DISPATCH_QUEUE_SERIAL);

    dispatch_group_enter(group);

    dispatch_group_async(group, serialQueue, ^{

        // 網路請求一

        [WebClick getDataSuccess:^(ResponseModel *model) {

            dispatch_group_leave(group);

        } failure:^(NSString *err) {

            dispatch_group_leave(group);

        }];

    });

    dispatch_group_enter(group);

    dispatch_group_async(group, serialQueue, ^{

        // 網路請求二

        [WebClick getDataSuccess:getBigTypeRM onSuccess:^(ResponseModel *model) {

            dispatch_group_leave(group);

        }                                  failure:^(NSString *errorString) {

            dispatch_group_leave(group);

        }];

    });

    dispatch_group_enter(group);

    dispatch_group_async(group, serialQueue, ^{

        // 網路請求三

        [WebClick getDataSuccess:^{

            dispatch_group_leave(group);

        } failure:^(NSString *errorString) {

            dispatch_group_leave(group);

        }];

    });

    // 所有網路請求結束後會來到這個方法

    dispatch_group_notify(group, serialQueue, ^{

        dispatch_async(dispatch_get_global_queue(0, 0), ^{

            dispatch_async(dispatch_get_main_queue(), ^{

                // 重新整理UI

            });

        });

});

66、解決openUrl延時問題

// 方法一

dispatch_async(dispatch_get_main_queue(), ^{

    UIApplication *application = [UIApplication sharedApplication];

    if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {

        [application openURL:URL options:@{}

           completionHandler:nil];

    } else {

        [application openURL:URL];

    }

    });

// 方法二

[self performSelector:@selector(redirectToURL:) withObject:url afterDelay:0.1];

- (void) redirectToURL

{

UIApplication *application = [UIApplication sharedApplication];

    if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {

        [application openURL:URL options:@{}

           completionHandler:nil];

    } else {

        [application openURL:URL];

    }

}

67、頁面跳轉實現翻轉動畫

// modal方式

    TestViewController *vc = [[TestViewController alloc] init];

    vc.view.backgroundColor = [UIColor redColor];

    vc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

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

// push方式

    TestViewController *vc = [[TestViewController alloc] init];

    vc.view.backgroundColor = [UIColor redColor];

    [UIView beginAnimations:@"View Flip" context:nil];

    [UIView setAnimationDuration:0.80];

    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];

    [self.navigationController pushViewController:vc animated:YES];

[UIView commitAnimations];

68、tableView實現無限滾動

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{

    CGFloat actualPosition = scrollView.contentOffset.y;

    CGFloat contentHeight = scrollView.contentSize.height - scrollView.frame.size.height;

    if (actualPosition >= contentHeight) {

        [self.dataArr addObjectsFromArray:self.dataArr];

        [self.tableView reloadData];

    }

}

69、程式碼方式調整螢幕亮度

// brightness屬性值在0-1之間,0代表最小亮度,1代表最大亮度

[[UIScreen mainScreen] setBrightness:0.5];

70、獲取當前應用CUP用量

float cpu_usage()

{

    kern_return_t kr;

    task_info_data_t tinfo;

    mach_msg_type_number_t task_info_count;

    task_info_count = TASK_INFO_MAX;

    kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);

    if (kr != KERN_SUCCESS) {

        return -1;

    }

    task_basic_info_t      basic_info;

    thread_array_t         thread_list;

    mach_msg_type_number_t thread_count;

    thread_info_data_t     thinfo;

    mach_msg_type_number_t thread_info_count;

    thread_basic_info_t basic_info_th;

    uint32_t stat_thread = 0; // Mach threads

    basic_info = (task_basic_info_t)tinfo;

    // get threads in the task

    kr = task_threads(mach_task_self(), &thread_list, &thread_count);

    if (kr != KERN_SUCCESS) {

        return -1;

    }

    if (thread_count > 0)

        stat_thread += thread_count;

    long tot_sec = 0;

    long tot_usec = 0;

    float tot_cpu = 0;

    int j;

    for (j = 0; j < (int)thread_count; j++)

    {

        thread_info_count = THREAD_INFO_MAX;

        kr = thread_info(thread_list[j], THREAD_BASIC_INFO,

                         (thread_info_t)thinfo, &thread_info_count);

        if (kr != KERN_SUCCESS) {

            return -1;

        }

        basic_info_th = (thread_basic_info_t)thinfo;

        if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {

            tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;

            tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds;

            tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;

        }

    } // for each thread

    kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));

    assert(kr == KERN_SUCCESS);

    return tot_cpu;

}

71、float資料取整四捨五入

    CGFloat f = 4.65;

    NSLog(@"%d", (int)f);    // 列印結果4

    CGFloat f = 4.65;

NSLog(@"%d", (int)round(f));    // 列印結果5

72、刪除UISearchBar系統預設邊框

    // 方法一

    searchBar.searchBarStyle = UISearchBarStyleMinimal;

    // 方法二

    [searchBar setBackgroundImage:[[UIImage alloc]init]];

    // 方法三

searchBar.barTintColor = [UIColor whiteColor];

73、為UICollectionViewCell設定圓角和陰影

cell.contentView.layer.cornerRadius = 2.0f;

cell.contentView.layer.borderWidth = 1.0f;

cell.contentView.layer.borderColor = [UIColor clearColor].CGColor;

cell.contentView.layer.masksToBounds = YES;

cell.layer.shadowColor = [UIColor lightGrayColor].CGColor;

cell.layer.shadowOffset = CGSizeMake(0, 2.0f);

cell.layer.shadowRadius = 2.0f;

cell.layer.shadowOpacity = 1.0f;

cell.layer.masksToBounds = NO;

cell.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds cornerRadius:cell.contentView.layer.cornerRadius].CGPath;

74、讓正在滑動的scrollView停止滾動(不是禁止,而是暫時停止滾動)

[scrollView setContentOffset:scrollView.contentOffset animated:NO];

76、根據經緯度獲取城市等資訊

// 建立經緯度

    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

    //建立一個譯碼器

    CLGeocoder *cLGeocoder = [[CLGeocoder alloc] init];

    [cLGeocoder reverseGeocodeLocation:userLocation completionHandler:^(NSArray *placemarks, NSError *error) {

        CLPlacemark *place = [placemarks objectAtIndex:0];

        // 位置名

NSLog(@"name,%@",place.name);

      // 街道

      NSLog(@"thoroughfare,%@",place.thoroughfare);

      // 子街道

      NSLog(@"subThoroughfare,%@",place.subThoroughfare);

      // 市

      NSLog(@"locality,%@",place.locality);

      // 區

      NSLog(@"subLocality,%@",place.subLocality);

      // 國家

      NSLog(@"country,%@",place.country);

        }

    }];

/*  CLPlacemark中屬性含義

name                    地名

thoroughfare            街道

subThoroughfare        街道相關資訊,例如門牌等

locality                城市

subLocality            城市相關資訊,例如標誌性建築

administrativeArea      直轄市

subAdministrativeArea  其他行政區域資訊(自治區等)

postalCode              郵編

ISOcountryCode          國家編碼

country                國家

inlandWater            水源,湖泊

ocean                  海洋

areasOfInterest        關聯的或利益相關的地標

*/

77、如何防止新增多個NSNotification觀察者?

// 解決方案就是新增觀察者之前先移除下這個觀察者

[[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];

[[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];

78、將一個xib新增到另外一個xib上

// 假設你的自定義view名字為CustomView,你需要在CustomView.m中重寫 `- (instancetype)initWithCoder:(NSCoder *)aDecoder` 方法,程式碼如下:

- (instancetype)initWithCoder:(NSCoder *)aDecoder {

    if ((self = [super initWithCoder:aDecoder])) {

        [self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0]];

    }

    return self;

}


1339326-aeec79df01be4dff.png

將一個xib新增到另外一個xib上.png

79、處理字串,使其首字母大寫

    NSString *str = @"abcdefghijklmn";

    NSString *resultStr;

    if (str && str.length > 0) {

        resultStr = [str stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[str substringToIndex:1] capitalizedString]];

    }

NSLog(@"%@", resultStr);

80、判斷一個UIAlertView/UIAlertController是否顯示

// UIAlertView自帶屬性

if (alert.visible)

{

      NSLog(@"顯示了");

} else {

      NSLog(@"未顯示");

}

// UIAlertController沒有visible屬性,需要自己判斷,新增一個全域性變數 BOOL visible

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"ActionTitle" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        self.visible = NO;

    }];

    UIAlertAction *calcelAction = [UIAlertAction actionWithTitle:@"calcelTitle" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        self.visible = NO;

    }];

    [alertController addAction:alertAction];

    [alertController addAction:calcelAction];

    [self presentViewController:alertController animated:YES completion:^{

        self.visible = YES;

}];

81、獲取字串中的數字

- (NSString *)getNumberFromStr:(NSString *)str

{

    NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

    return [[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];

}

NSLog(@"%@", [self getNumberFromStr:@"a0b0c1d2e3f4fda8fa8fad9fsad23"]); // 00123488923

82、為UIView的某個方向新增邊框

// 新增UIView分類

// UIView+WZB.h

#import

/**

邊框方向

- WZBBorderDirectionTop: 頂部

- WZBBorderDirectionLeft: 左邊

- WZBBorderDirectionBottom: 底部

- WZBBorderDirectionRight: 右邊

*/

typedef NS_ENUM(NSInteger, WZBBorderDirectionType) {

    WZBBorderDirectionTop = 0,

    WZBBorderDirectionLeft,

    WZBBorderDirectionBottom,

    WZBBorderDirectionRight

};

@interface UIView (WZB)

/**

為UIView的某個方向新增邊框

@param direction 邊框方向

@param color 邊框顏色

@param width 邊框寬度

*/

- (void)wzb_addBorder:(WZBBorderDirectionType)direction color:(UIColor *)color width:(CGFloat)width;

@end

// UIView+WZB.m

#import "UIView+WZB.h"

@implementation UIView (WZB)

- (void)wzb_addBorder:(WZBBorderDirectionType)direction color:(UIColor *)color width:(CGFloat)width

{

    CALayer *border = [CALayer layer];

    border.backgroundColor = color.CGColor;

    switch (direction) {

        case WZBBorderDirectionTop:

        {

            border.frame = CGRectMake(0.0f, 0.0f, self.bounds.size.width, width);

        }

            break;

        case WZBBorderDirectionLeft:

        {

            border.frame = CGRectMake(0.0f, 0.0f, width, self.bounds.size.height);

        }

            break;

        case WZBBorderDirectionBottom:

        {

            border.frame = CGRectMake(0.0f, self.bounds.size.height - width, self.bounds.size.width, width);

        }

            break;

        case WZBBorderDirectionRight:

        {

            border.frame = CGRectMake(self.bounds.size.width - width, 0, width, self.bounds.size.height);

        }

            break;

        default:

            break;

    }

    [self.layer addSublayer:border];

}

83、通過屬性設定UISwitch、UIProgressView等控制元件的寬高

mySwitch.transform = CGAffineTransformMakeScale(5.0f, 5.0f);

progressView.transform = CGAffineTransformMakeScale(5.0f, 5.0f);

84、自動搜尋功能,使用者連續輸入的時候不搜尋,使用者停止輸入的時候自動搜尋(我這裡設定的是0.5s,可根據需求更改)

// 輸入框文字改變的時候呼叫

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    // 先取消呼叫搜尋方法

    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchNewResult) object:nil];

    // 0.5秒後呼叫搜尋方法

    [self performSelector:@selector(searchNewResult) withObject:nil afterDelay:0.5];

}

85、修改UISearchBar的佔位文字顏色

    // 方法一(推薦使用)

    UITextField *searchField = [searchBar valueForKey:@"_searchField"];

    [searchField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];

    // 方法二(已過期)

    [[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];

    // 方法三(已過期)

    NSDictionary *placeholderAttributes = @{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:15],};

    NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:searchBar.placeholder attributes:placeholderAttributes];

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setAttributedPlaceholder:attributedPlaceholder];

86、某個介面多個事件同時響應引起的問題(比如,兩個button同時按push到新介面,兩個都會響應,可能導致push重疊)

// UIView有個屬性叫做exclusiveTouch,設定為YES後,其響應事件會和其他view互斥(有其他view事件響應的時候點選它不起作用)

view.exclusiveTouch = YES;

// 一個一個設定太麻煩了,可以全域性設定

[[UIView appearance] setExclusiveTouch:YES];

// 或者只設定button

[[UIButton appearance] setExclusiveTouch:YES];

87、修改tabBar的frame

// 子類化UITabBarViewController,我這裡以修改tabBar高度為例,重寫viewWillLayoutSubviews方法

#import "WZBTabBarViewController.h"

@interface WZBTabBarViewController ()

@end

@implementation WZBTabBarViewController

- (void)viewWillLayoutSubviews {

    CGRect tabFrame = self.tabBar.frame;

    tabFrame.size.height = 100;

    tabFrame.origin.y = self.view.frame.size.height - 100;

    self.tabBar.frame = tabFrame;

}

@end

88、修改鍵盤背景顏色

// 設定某個鍵盤顏色

    textField.keyboardAppearance = UIKeyboardAppearanceAlert;

// 設定工程中所有鍵盤顏色

[[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceAlert];

89、修改image顏色

UIImage *image = [UIImage imageNamed:@"test"];

    imageView.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextClipToMask(context, rect, image.CGImage);

    CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]);

    CGContextFillRect(context, rect);

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    UIImage *flippedImage = [UIImage imageWithCGImage:img.CGImage scale:1.0 orientation: UIImageOrientationDownMirrored];

imageView.image = flippedImage;

90、動畫執行removeFromSuperview

    [UIView animateWithDuration:0.2

                     animations:^{

                         view.alpha = 0.0f;

                     } completion:^(BOOL finished){

                         [view removeFromSuperview];

}];

91、啟動頁顯示延時

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

//  延時10s

    sleep(10);

    return YES;

}

92、設定UIButton高亮時的背景顏色

// 方法一、子類化UIButton,重寫setHighlighted:方法,程式碼如下

#import "WZBButton.h"

@implementation WZBButton

- (void)setHighlighted:(BOOL)highlighted {

    [super setHighlighted:highlighted];

    UIColor *normalColor = [UIColor greenColor];

    UIColor *highlightedColor = [UIColor redColor];

    self.backgroundColor = highlighted ? highlightedColor : normalColor;

}

// 方法二、利用setBackgroundImage:forState:方法

[button setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forState:UIControlStateHighlighted];

- (UIImage *)imageWithColor:(UIColor *)color {

    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}

93、關於圖片拉伸

推薦看這個部落格,講的很詳細http://blog.csdn.net/q199109106q/article/details/8615661

94、利用runtime獲取一個類所有屬性

- (NSArray *)allPropertyNames:(Class)aClass

{

    unsigned count;

    objc_property_t *properties = class_copyPropertyList(aClass, &count);

    NSMutableArray *rv = [NSMutableArray array];

    unsigned i;

    for (i = 0; i < count; i++)

    {

        objc_property_t property = properties[i];

        NSString *name = [NSString stringWithUTF8String:property_getName(property)];

        [rv addObject:name];

    }

    free(properties);

    return rv;

}

95、設定textView的某段文字變成其他顏色

- (void)setupTextView:(UITextView *)textView text:(NSString *)text color:(UIColor *)color {

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:textView.text];

    [string addAttribute:NSForegroundColorAttributeName value:color range:[textView.text rangeOfString:text]];

    [textView setAttributedText:string];

}

96、讓push跳轉動畫像modal跳轉動畫那樣效果(從下往上推上來)

- (void)push

{

TestViewController *vc = [[TestViewController alloc] init];

    vc.view.backgroundColor = [UIColor redColor];

    CATransition* transition = [CATransition animation];

    transition.duration = 0.4f;

    transition.type = kCATransitionMoveIn;

    transition.subtype = kCATransitionFromTop;

    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];

    [self.navigationController pushViewController:vc animated:NO];

}

- (void)pop

{

CATransition* transition = [CATransition animation];

    transition.duration = 0.4f;

    transition.type = kCATransitionReveal;

    transition.subtype = kCATransitionFromBottom;

    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];

    [self.navigationController popViewControllerAnimated:NO];

}

97、上傳圖片太大,壓縮圖片

-(UIImage *)resizeImage:(UIImage *)image

{

    float actualHeight = image.size.height;

    float actualWidth = image.size.width;

    float maxHeight = 300.0;

    float maxWidth = 400.0;

    float imgRatio = actualWidth/actualHeight;

    float maxRatio = maxWidth/maxHeight;

    float compressionQuality = 0.5;//50 percent compression

    if (actualHeight > maxHeight || actualWidth > maxWidth)

    {

        if(imgRatio < maxRatio)

        {

            //adjust width according to maxHeight

            imgRatio = maxHeight / actualHeight;

            actualWidth = imgRatio * actualWidth;

            actualHeight = maxHeight;

        }

        else if(imgRatio > maxRatio)

        {

            //adjust height according to maxWidth

            imgRatio = maxWidth / actualWidth;

            actualHeight = imgRatio * actualHeight;

            actualWidth = maxWidth;

        }

        else

        {

            actualHeight = maxHeight;

            actualWidth = maxWidth;

        }

    }

    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);

    UIGraphicsBeginImageContext(rect.size);

    [image drawInRect:rect];

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);

    UIGraphicsEndImageContext();

    return [UIImage imageWithData:imageData];

}

相關文章