美文网首页
iOS开发零碎知识点

iOS开发零碎知识点

作者: 守候的流年 | 来源:发表于2017-02-10 09:35 被阅读27次

记录一下不常用,但是很实用的知识点,有错误请指出,我会更正,有好的知识点也可以提出,我添加上,希望大家共同进步。

  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、设置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.当使用-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:5.0];
    }
  1. 查询系统所有字体
    // 打印字体
    for (id familyName in [UIFont familyNames]) {
        NSLog(@"%@", familyName);
        for (id fontName in [UIFont fontNamesForFamilyName:familyName]) NSLog(@"  %@", fontName);
    }
    // 也可以进入这个网址查看 http://iosfonts.com/
  1. 随机数-可以根据需要自行扩展吧
    NSInteger i = arc4random();
  2. 判断一个字符串是否为数字
NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([str rangeOfCharacterFromSet:notDigits].location == NSNotFound)
    {
      // 是数字
    } else
    {
      // 不是数字
    }
  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、让导航控制器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
        //默认
    }else if(orientation == UIInterfaceOrientationPortrait){
        //竖屏
    }else if(orientation == UIInterfaceOrientationLandscapeLeft){
        // 左横屏
    }else if(orientation == UIInterfaceOrientationLandscapeRight) {
        //右横屏        
    }

16、设置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;

17、在应用中打开设置的某个界面

// 打开设置->通用
[[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

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光标

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内部背景颜色
    UISearchBar *searchBar = [_searchBar valueForKey:@"_searchField"];
    searchBar.backgroundColor = [UIColor redColor];
2️⃣
   //删除UISearchBar系统默认边框
   // 方法一
    searchBar.searchBarStyle = UISearchBarStyleMinimal;
    // 方法二
    [searchBar setBackgroundImage:[[UIImage alloc]init]];
    // 方法三
    searchBar.barTintColor = [UIColor whiteColor];

3️⃣
    //自动搜索功能,用户连续输入的时候不搜索,用户停止输入的时候自动搜索(我这里设置的是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];
}

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、通知 - 监听APP生命周期

UIApplicationDidEnterBackgroundNotification 应用程序进入后台
UIApplicationWillEnterForegroundNotification 应用程序将要进入前台
UIApplicationDidFinishLaunchingNotification 应用程序完成启动
UIApplicationDidFinishLaunchingNotification 应用程序由挂起变的活跃
UIApplicationWillResignActiveNotification 应用程序挂起(有电话进来或者锁屏)
UIApplicationDidReceiveMemoryWarningNotification 应用程序收到内存警告
UIApplicationDidReceiveMemoryWarningNotification 应用程序终止(后台杀死、手机关机等) 

UIApplicationSignificantTimeChangeNotification 当有重大时间改变(凌晨0点,设备时间被修改,时区改变等)

UIApplicationWillChangeStatusBarOrientationNotification 设备方向将要改变
UIApplicationDidChangeStatusBarOrientationNotification 设备方向改变

UIApplicationWillChangeStatusBarFrameNotification 设备状态栏frame将要改变
UIApplicationDidChangeStatusBarFrameNotification 设备状态栏frame改变

UIApplicationBackgroundRefreshStatusDidChangeNotification 应用程序在后台下载内容的状态发生变化

UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件被锁定,无法访问
UIApplicationProtectedDataWillBecomeUnavailable 本地受保护的文件可用了

23、触摸事件类型

UIControlEventTouchCancel 取消控件当前触发的事件
UIControlEventTouchDown 点按下去的事件
UIControlEventTouchDownRepeat 重复的触动事件
UIControlEventTouchDragEnter 手指被拖动到控件的边界的事件
UIControlEventTouchDragExit 一个手指从控件内拖到外界的事件
UIControlEventTouchDragInside 手指在控件的边界内拖动的事件
UIControlEventTouchDragOutside 手指在控件边界之外被拖动的事件
UIControlEventTouchUpInside 手指处于控制范围内的触摸事件  (一般都是用这个)
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、页面跳转实现翻转动画

    // 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实现无限滚动-到了底部继续加载更多数据

- (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、根据经纬度获取城市等信息

// 创建经纬度
    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           关联的或利益相关的地标
*/

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、获取字符串中的数字

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

32、通过属性设置UISwitch、UIProgressView等控件的宽高

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

33、某个界面多个事件同时响应引起的问题(比如,两个button同时按push到新界面,两个都会响应,可能导致push重叠)

// UIView有个属性叫做exclusiveTouch,设置为YES后,其响应事件会和其他view互斥(有其他view事件响应的时候点击它不起作用)
view.exclusiveTouch = YES;

// 一个一个设置太麻烦了,可以全局设置
[[UIView appearance] setExclusiveTouch:YES];

// 或者只设置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、修改键盘背景颜色

// 设置某个键盘颜色
textField.keyboardAppearance = UIKeyboardAppearanceAlert;

// 设置工程中所有键盘颜色
[[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跳转动画像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];
}

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、


相关文章

  • iOS零碎知识点<高阶版>

    iOS零碎知识点<初级版>iOS零碎知识点<中阶版>iOS零碎知识点<高阶版>iOS零碎知识点<工具篇>

  • iOS零碎知识点<工具篇>

    iOS零碎知识点<初级版>iOS零碎知识点<中阶版>iOS零碎知识点<中阶版>iOS零碎知识点<工具篇>

  • iOS零碎知识点<中阶版>

    iOS零碎知识点<初级版>iOS零碎知识点<中阶版>iOS零碎知识点<高阶版>iOS零碎知识点<工具篇> 获取属性...

  • iOS零碎知识点<初级版>

    iOS零碎知识点<初级版>iOS零碎知识点<中阶版>iOS零碎知识点<高阶版>iOS零碎知识点<工具篇> 优雅的隐...

  • iOS开发零碎知识点

    本篇文章记录了iOS开发零碎知识点,简单又实用! 代码写了这么多,但是总是有些知识点在真正需要用到的时候却遗忘了,...

  • iOS开发零碎知识点

    以下这篇文章纯属个人记录到自己的简书上,非本人积累,查看原文在此。 记录一些常用和不常用的iOS知识点,防止遗忘丢...

  • iOS开发零碎知识点

    记录一下不常用,但是很实用的知识点,有错误请指出,我会更正,有好的知识点也可以提出,我添加上,希望大家共同进步。 ...

  • iOS开发零碎知识点

    引自:http://m.blog.csdn.net/article/details?id=52180380 记录一...

  • iOS开发零碎知识点

    UITableView分割线置顶 1.NSArray 快速求总&&最大值&&最小值&&平均值 获取沙盒根目录 2....

  • iOS开发Swift知识点总结(一)

    iOS开发Swift知识点总结(一)

网友评论

      本文标题:iOS开发零碎知识点

      本文链接:https://www.haomeiwen.com/subject/wwqgittx.html