iOS開發(fā)零碎知識點

記錄一下不常用,但是很實用的知識點,有錯誤請指出,我會更正,有好的知識點也可以提出,我添加上,希望大家共同進步。

  1. 去掉UITableView多余的分割線
    tableView.tableFooterView =[ [UIView alloc] init];
  2. 、用十六進制獲取UIColor(類方法或者Category都可以,這里我用工具類方法)
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];```
    // String should be 6 or 8 characters
    if ([cString length] < 6) { return [UIColor clearColor]; }
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) 
      cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
      cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
      return [UIColor clearColor];
    
   // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
   NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2; NSString *gString = [cString substringWithRange:range];
    //b
   range.location = 4; NSString *bString = [cString substringWithRange:range];`
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];```
    
   return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
  1. 禁止程序運行時自動鎖屏
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
  2. 強制讓App直接退出(非閃退,非崩潰)
    - (void)exitApplication {
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;
        [UIView animateWithDuration:1.0f animations:^{
         window.alpha = 0;
        } completion:^(BOOL finished) {
        exit(0);
        }];
    }
  1. 修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"請輸入用戶名";  
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];  
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

6、設(shè)置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;

// 或者使用xib,看下gif圖


1499657090104458.gif

7.當(dāng)使用-performSelector:withObject:withObject:afterDelay:方法時,需要傳入多參數(shù)問題

// 方法一、
// 把參數(shù)放進一個數(shù)組/字典,直接把數(shù)組/字典當(dāng)成一個參數(shù)傳過去,具體方法實現(xiàn)的地方再解析這個數(shù)組/字典
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:5.0];
    }
  1. 查詢系統(tǒng)所有字體
    // 打印字體
    for (id familyName in [UIFont familyNames]) {
        NSLog(@"%@", familyName);
        for (id fontName in [UIFont fontNamesForFamilyName:familyName]) NSLog(@"  %@", fontName);
    }
    // 也可以進入這個網(wǎng)址查看 http://iosfonts.com/
  1. 隨機數(shù)-可以根據(jù)需要自行擴展吧
    NSInteger i = arc4random();
  2. 判斷一個字符串是否為數(shù)字
NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound)
    {
      // 是數(shù)字
    } else
    {
      // 不是數(shù)字
    }
  1. 將一個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);
}

12、保存UIImage到本地

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

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

13、鍵盤上方增加工具欄

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;

14、讓導(dǎo)航控制器pop回指定的控制器

NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
for (UIViewController *aViewController in allViewControllers) {
    if ([aViewController isKindOfClass:[RequiredViewController class]]) {
        [self.navigationController popToViewController:aViewController animated:NO];
    }
}

15、獲取屏幕方向

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    if(orientation == 0) {//Default orientation
        //默認(rèn)
    }else if(orientation == UIInterfaceOrientationPortrait){
        //豎屏
    }else if(orientation == UIInterfaceOrientationLandscapeLeft){
        // 左橫屏
    }else if(orientation == UIInterfaceOrientationLandscapeRight) {
        //右橫屏        
    }

16、設(shè)置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設(shè)置透明度
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"yourImage"]];
imageView.alpha = 0.5;

17、在應(yīng)用中打開設(shè)置的某個界面

// 打開設(shè)置->通用
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=General"]];

// 以下是設(shè)置其他界面
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

18、在UITextView中顯示html文本

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 30, 100, 199)];
    textView.backgroundColor = [UIColor redColor];
    [self.view addSubview:textView];
    NSString *htmlString = @"
![](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;

19、隱藏UITextView/UITextField光標(biāo)

textField.tintColor = [UIColor clearColor];

20、獲取隨機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;
    }

21、修改UISearBar

1??
    //修改UISearBar內(nèi)部背景顏色
    UISearchBar *searchBar = [_searchBar valueForKey:@"_searchField"];
    searchBar.backgroundColor = [UIColor redColor];
2??
   //刪除UISearchBar系統(tǒng)默認(rèn)邊框
   // 方法一
    searchBar.searchBarStyle = UISearchBarStyleMinimal;
    // 方法二
    [searchBar setBackgroundImage:[[UIImage alloc]init]];
    // 方法三
    searchBar.barTintColor = [UIColor whiteColor];

3??
    //自動搜索功能,用戶連續(xù)輸入的時候不搜索,用戶停止輸入的時候自動搜索(我這里設(shè)置的是0.5s,可根據(jù)需求更改)
    // 輸入框文字改變的時候調(diào)用
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    // 先取消調(diào)用搜索方法
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchNewResult) object:nil];
    // 0.5秒后調(diào)用搜索方法
    [self performSelector:@selector(searchNewResult) withObject:nil afterDelay:0.5];
}

4??
  //修改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];


22、通知 - 監(jiān)聽APP生命周期

UIApplicationDidEnterBackgroundNotification 應(yīng)用程序進入后臺
UIApplicationWillEnterForegroundNotification 應(yīng)用程序?qū)⒁M入前臺
UIApplicationDidFinishLaunchingNotification 應(yīng)用程序完成啟動
UIApplicationDidFinishLaunchingNotification 應(yīng)用程序由掛起變的活躍
UIApplicationWillResignActiveNotification 應(yīng)用程序掛起(有電話進來或者鎖屏)
UIApplicationDidReceiveMemoryWarningNotification 應(yīng)用程序收到內(nèi)存警告
UIApplicationDidReceiveMemoryWarningNotification 應(yīng)用程序終止(后臺殺死、手機關(guān)機等) 

UIApplicationSignificantTimeChangeNotification 當(dāng)有重大時間改變(凌晨0點,設(shè)備時間被修改,時區(qū)改變等)

UIApplicationWillChangeStatusBarOrientationNotification 設(shè)備方向?qū)⒁淖?UIApplicationDidChangeStatusBarOrientationNotification 設(shè)備方向改變

UIApplicationWillChangeStatusBarFrameNotification 設(shè)備狀態(tài)欄frame將要改變
UIApplicationDidChangeStatusBarFrameNotification 設(shè)備狀態(tài)欄frame改變

UIApplicationBackgroundRefreshStatusDidChangeNotification 應(yīng)用程序在后臺下載內(nèi)容的狀態(tài)發(fā)生變化

UIApplicationProtectedDataWillBecomeUnavailable 本地受保護的文件被鎖定,無法訪問
UIApplicationProtectedDataWillBecomeUnavailable 本地受保護的文件可用了

23、觸摸事件類型

UIControlEventTouchCancel 取消控件當(dāng)前觸發(fā)的事件
UIControlEventTouchDown 點按下去的事件
UIControlEventTouchDownRepeat 重復(fù)的觸動事件
UIControlEventTouchDragEnter 手指被拖動到控件的邊界的事件
UIControlEventTouchDragExit 一個手指從控件內(nèi)拖到外界的事件
UIControlEventTouchDragInside 手指在控件的邊界內(nèi)拖動的事件
UIControlEventTouchDragOutside 手指在控件邊界之外被拖動的事件
UIControlEventTouchUpInside 手指處于控制范圍內(nèi)的觸摸事件  (一般都是用這個)
UIControlEventTouchUpOutside 手指超出控制范圍的控制中的觸摸事件

24、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;
}

25、去除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;
                }
            }
        }
    }

26、頁面跳轉(zhuǎn)實現(xiàn)翻轉(zhuǎn)動畫

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

27、 tableView實現(xiàn)無限滾動-到了底部繼續(xù)加載更多數(shù)據(jù)

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

28、根據(jù)經(jīng)緯度獲取城市等信息

// 創(chuàng)建經(jīng)緯度
    CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    //創(chuàng)建一個譯碼器
    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);
      // 區(qū)
      NSLog(@"subLocality,%@",place.subLocality); 
      // 國家
      NSLog(@"country,%@",place.country);
    }];

/*  CLPlacemark中屬性含義
name                      地名
thoroughfare              街道
subThoroughfare           街道相關(guān)信息,例如門牌等
locality                  城市
subLocality               城市相關(guān)信息,例如標(biāo)志性建筑
administrativeArea        直轄市
subAdministrativeArea     其他行政區(qū)域信息(自治區(qū)等)
postalCode                郵編
ISOcountryCode            國家編碼
country                   國家
inlandWater               水源,湖泊
ocean                     海洋
areasOfInterest           關(guān)聯(lián)的或利益相關(guān)的地標(biāo)
*/

29、如何防止添加多個NSNotification觀察者?

// 解決方案就是添加觀察者之前先移除下這個觀察者
[[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];
[[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];

30、判斷一個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;
    }];

31、獲取字符串中的數(shù)字

- (NSString *)getNumberFromStr:(NSString *)str {
    NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    return [[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}
    NSLog(@"%@", [self getNumberFromStr:@"0b0c1d2e3f4fda8fa8fad9fsad23"]); // 00123488923

32、通過屬性設(shè)置UISwitch、UIProgressView等控件的寬高

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

33、某個界面多個事件同時響應(yīng)引起的問題(比如,兩個button同時按push到新界面,兩個都會響應(yīng),可能導(dǎo)致push重疊)

// UIView有個屬性叫做exclusiveTouch,設(shè)置為YES后,其響應(yīng)事件會和其他view互斥(有其他view事件響應(yīng)的時候點擊它不起作用)
view.exclusiveTouch = YES;

// 一個一個設(shè)置太麻煩了,可以全局設(shè)置
[[UIView appearance] setExclusiveTouch:YES];

// 或者只設(shè)置button
[[UIButton appearance] setExclusiveTouch:YES];

34、修改tabBar的frame

// 子類化UITabBarViewController,我這里以修改tabBar高度為例,重寫viewWillLayoutSubviews方法
#import "CustomTabBarViewController.h"

@interface CustomTabBarViewController ()

@end

@implementation CustomTabBarViewController
- (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

35、修改鍵盤背景顏色

// 設(shè)置某個鍵盤顏色
textField.keyboardAppearance = UIKeyboardAppearanceAlert;

// 設(shè)置工程中所有鍵盤顏色
[[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceAlert];

36、利用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;
}

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

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

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

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

}

39、


40、


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,646評論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,595評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,560評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,035評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,814評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,224評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,301評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,444評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,988評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,804評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,998評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,544評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,237評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,665評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,927評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,706評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,993評論 2 374

推薦閱讀更多精彩內(nèi)容