iOS开发零碎知识点

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

  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、


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容