ios 生僻小技巧和总结

时间:2021-07-03 02:38:31
 

链接:http://www.jianshu.com/p/1ff9e44ccc78

3、禁用button高亮

button.adjustsImageWhenHighlighted = NO;或者在创建的时候 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

4、tableview遇到这种报错failed to obtain a cell from its dataSource

是因为你的cell被调用的早了。先循环使用了cell,后又创建cell。顺序错了
可能原因:1、xib的cell没有注册 2、内存中已经有这个cell的缓存了(也就是说通过你的cellId找到的cell并不是你想要的类型),这时候需要改下cell的标识

5、cocoa pods报这个错误:unable to access 'https://github.com/facebook/pop.git/': Operation timed out after 0 milliseconds with 0 out of 0 bytes received

解决办法:原因可能是网络问题,网络请求超时了,只需要重试就行了

6、cocoa pods 出现ERROR: While executing gem ... (Errno::EPERM)

解决办法:
https://segmentfault.com/q/1010000002926243


8、去除数组中重复的对象

NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self"];

9、编译的时候遇到 no such file or directory: /users/apple/XXX

是因为编译的时候,在此路径下找不到这个文件,解决这个问题,首先是是要检查缺少的文件是不是在工程中,如果不在工程中,需要从本地拖进去,如果发现已经存在工程中了,或者拖进去还是报错,这时候需要去build phases中搜索这个文件,这时候很可能会搜出现两个相同的文件,这时候,有一个路径是正确的,删除另外一个即可。如果删除了还是不行,需要把两个都删掉,然后重新往工程里拖进这个文件即可

ios 生僻小技巧和总结
build phases

13、SDWebImage本地缓存策略需要注意。如果之前缓存过一张图片,即使下次服务器换了这张图片,但是图片url没换,用sdwebimage下载下来的还是以前那张,所以遇到这种问题,不要先去怼服务器,清空下缓存再试就好了。

17、开发中如果要动态修改tableView的tableHeaderView或者tableFooterView的高度,需要给tableView重新设置,而不是直接更改高度。正确的做法是重新设置一下tableView.tableFooterView = 更改过高度的view。为什么?其实在iOS8以上直接改高度是没有问题的,在iOS8中出现了contentSize不准确的问题,这是解决办法。

20、设置navigationBar上的title颜色和大小

    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}]

31、自定义NSLog

#define NSLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

44、模型转字典

static NSSet *classes;- (NSMutableDictionary *)getParameterDictionary {    NSMutableDictionary *dict = [NSMutableDictionary dictionary];    Class c = self.class;    while (c) {        unsigned count;        objc_property_t *properties = class_copyPropertyList([c class], &count);        for (int i = 0; i < count; i++) {            NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];            dict[key] = [self valueForKey:key];        }        free(properties);        // 获得父类        c = class_getSuperclass(c);        if ([self isClassFromFoundation:c]) break;    }    return dict;}- (BOOL)isClassFromFoundation:(Class)c{    if (c == [NSObject class] || c == [NSManagedObject class]) return YES;    __block BOOL result = NO;    [[self foundationClasses] enumerateObjectsUsingBlock:^(Class foundationClass, BOOL *stop) {        if ([c isSubclassOfClass:foundationClass]) {            result = YES;            *stop = YES;        }    }];    return result;}- (NSSet *)foundationClasses{    if (classes == nil) {        // 集合中没有NSObject,因为几乎所有的类都是继承自NSObject,具体是不是NSObject需要特殊判断        classes = [NSSet setWithObjects:                              [NSURL class],                              [NSDate class],                              [NSValue class],                              [NSData class],                              [NSError class],                              [NSArray class],                              [NSDictionary class],                              [NSString class],                              [NSAttributedString class], nil];    }    return classes;}

49、长按复制功能

- (void)viewDidLoad{    [self.view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pasteBoard:)]];}- (void)pasteBoard:(UILongPressGestureRecognizer *)longPress {    if (longPress.state == UIGestureRecognizerStateBegan) {        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];        pasteboard.string = @"需要复制的文本";    }}

52、判断图片类型

//通过图片Data数据第一个字节 来获取图片扩展名- (NSString *)contentTypeForImageData:(NSData *)data{    uint8_t c;    [data getBytes:&c length:1];    switch (c)    {        case 0xFF:            return @"jpeg";        case 0x89:            return @"png";        case 0x47:            return @"gif";        case 0x49:        case 0x4D:            return @"tiff";        case 0x52:        if ([data length] < 12) {            return nil;        }        NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];        if ([testString hasPrefix:@"RIFF"]            && [testString hasSuffix:@"WEBP"])        {            return @"webp";        }        return nil;    }    return nil;}

54、获取一个类的所有属性

id LenderClass = objc_getClass("Lender");unsigned int outCount, i;objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);for (i = 0; i < outCount; i++) {    objc_property_t property = properties[i];    fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));}

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

56、image拉伸

+ (UIImage *)resizableImage:(NSString *)imageName{    UIImage *image = [UIImage imageNamed:imageName];    CGFloat imageW = image.size.width;    CGFloat imageH = image.size.height;    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(imageH * 0.5, imageW * 0.5, imageH * 0.5, imageW * 0.5) resizingMode:UIImageResizingModeStretch];}

61、拿到当前正在显示的控制器,不管是push进去的,还是present进去的都能拿到

- (UIViewController *)getVisibleViewControllerFrom:(UIViewController*)vc {    if ([vc isKindOfClass:[UINavigationController class]]) {        return [self getVisibleViewControllerFrom:[((UINavigationController*) vc) visibleViewController]];    }else if ([vc isKindOfClass:[UITabBarController class]]){        return [self getVisibleViewControllerFrom:[((UITabBarController*) vc) selectedViewController]];    } else {        if (vc.presentedViewController) {            return [self getVisibleViewControllerFrom:vc.presentedViewController];        } else {            return vc;        }    }}

64、KVO监听某个对象的属性

// 添加监听者[self addObserver:self forKeyPath:property options:NSKeyValueObservingOptionNew context:nil];// 当监听的属性值变化的时候会来到这个方法- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {    if ([keyPath isEqualToString:@"property"]) {       [self textViewTextChange];       } else {     }}

72、合并两个图片

+ (UIImage*)mergeImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {    CGImageRef firstImageRef = firstImage.CGImage;    CGFloat firstWidth = CGImageGetWidth(firstImageRef);    CGFloat firstHeight = CGImageGetHeight(firstImageRef);    CGImageRef secondImageRef = secondImage.CGImage;    CGFloat secondWidth = CGImageGetWidth(secondImageRef);    CGFloat secondHeight = CGImageGetHeight(secondImageRef);    CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));    UIGraphicsBeginImageContext(mergedSize);    [firstImage drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];    [secondImage drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)];    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    return image;}

74、为imageView添加倒影

    CGRect frame = self.frame;    frame.origin.y += (frame.size.height + 1);    UIImageView *reflectionImageView = [[UIImageView alloc] initWithFrame:frame];    self.clipsToBounds = TRUE;    reflectionImageView.contentMode = self.contentMode;    [reflectionImageView setImage:self.image];    reflectionImageView.transform = CGAffineTransformMakeScale(1.0, -1.0);    CALayer *reflectionLayer = [reflectionImageView layer];    CAGradientLayer *gradientLayer = [CAGradientLayer layer];    gradientLayer.bounds = reflectionLayer.bounds;    gradientLayer.position = CGPointMake(reflectionLayer.bounds.size.width / 2, reflectionLayer.bounds.size.height * 0.5);    gradientLayer.colors = [NSArray arrayWithObjects:                            (id)[[UIColor clearColor] CGColor],                            (id)[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] CGColor], nil];    gradientLayer.startPoint = CGPointMake(0.5,0.5);    gradientLayer.endPoint = CGPointMake(0.5,1.0);    reflectionLayer.mask = gradientLayer;    [self.superview addSubview:reflectionImageView];

75、画水印

// 画水印- (void) setImage:(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect{    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)    {        UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);    }    //原图    [image drawInRect:self.bounds];    //水印图    [mark drawInRect:rect];    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    self.image = newPic;}

76、让label的文字内容显示在左上/右上/左下/右下/中心顶/中心底部

自定义UILabel// 重写label的textRectForBounds方法- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {    CGRect rect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];    switch (self.textAlignmentType) {        case WZBTextAlignmentTypeLeftTop: {            rect.origin = bounds.origin;        }            break;        case WZBTextAlignmentTypeRightTop: {            rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, bounds.origin.y);        }            break;        case WZBTextAlignmentTypeLeftBottom: {            rect.origin = CGPointMake(bounds.origin.x, CGRectGetMaxY(bounds) - rect.size.height);        }            break;        case WZBTextAlignmentTypeRightBottom: {            rect.origin = CGPointMake(CGRectGetMaxX(bounds) - rect.size.width, CGRectGetMaxY(bounds) - rect.size.height);        }            break;        case WZBTextAlignmentTypeTopCenter: {            rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - rect.origin.y);        }            break;        case WZBTextAlignmentTypeBottomCenter: {            rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, CGRectGetMaxY(bounds) - CGRectGetMaxY(bounds) - rect.size.height);        }            break;        case WZBTextAlignmentTypeLeft: {            rect.origin = CGPointMake(0, rect.origin.y);        }            break;        case WZBTextAlignmentTypeRight: {            rect.origin = CGPointMake(rect.origin.x, 0);        }            break;        case WZBTextAlignmentTypeCenter: {            rect.origin = CGPointMake((CGRectGetWidth(bounds) - CGRectGetWidth(rect)) / 2, (CGRectGetHeight(bounds) - CGRectGetHeight(rect)) / 2);        }            break;        default:            break;    }    return rect;}- (void)drawTextInRect:(CGRect)rect {    CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];    [super drawTextInRect:textRect];}

77、scrollView上的输入框,键盘挡住的问题

推荐用IQKeyboardManager这个框架!手动解决如下1、监听键盘弹出/消失的通知2、在通知中加入代码:NSDictionary* info = [aNotification userInfo];CGRect keyPadFrame=[[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self.view];CGSize kbSize =keyPadFrame.size;CGRect activeRect=[self.view convertRect:activeField.frame fromView:activeField.superview];CGRect aRect = self.view.bounds;aRect.size.height -= (kbSize.height);CGPoint origin =  activeRect.origin;origin.y -= backScrollView.contentOffset.y;if (!CGRectContainsPoint(aRect, origin)) {    CGPoint scrollPoint = CGPointMake(0.0,CGRectGetMaxY(activeRect)-(aRect.size.height));    [backScrollView setContentOffset:scrollPoint animated:YES];}

78、frame布局的cell动态高度

这种通常在你的模型中添加一个辅助属性cellHeight,在模型中重写这个属性的get方法,根据你的布局和模型中的其他属性值计算出总高度。最后在tableView:heightForRow方法中,根据indexPath找出对应的模型,返回这个高度即可。

79、AutoLayout布局的cell动态高度

// 1、设置tableView的属性self.tableView.rowHeight = UITableViewAutomaticDimension;self.tableView.estimatedRowHeight = 44.0; // 这个属性非0,估计cell高度
// 2、至上而下设置cell的约束,注意,上下左右最好都要顶到cell的四周
ios 生僻小技巧和总结
cell

82、cell去除选中效果

cell.selectionStyle = UITableViewCellSelectionStyleNone;

83、cell点按效果

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {    [tableView deselectRowAtIndexPath:indexPath animated:YES];}

87、UITextView没有placeholder的问题?

网上有很多此类自定义控件,也可以参考下我写的一个UITextView分类 UITextView-WZB

90、获取一个视频的第一帧图片

    NSURL *url = [NSURL URLWithString:filepath];    AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];    AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];    generate1.appliesPreferredTrackTransform = YES;    NSError *err = NULL;    CMTime time = CMTimeMake(1, 2);    CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];    UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];    return one;

91、获取视频的时长

+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {    NSURL *videoUrl = [NSURL URLWithString:urlString];    AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];    CMTime time = [avUrl duration];    int seconds = ceil(time.value/time.timescale);    return seconds;}

98、UITableView (<UITableView: 0x7ff19b027000; >) failed to obtain a cell from its dataSource (<ViewController: 0x7ff19a507520>)

这个错误原因是tableView的代理方法-tableView:cellForRowAtIndexPath:需要返回一个UITableViewCell,而你返回了一个nil。另外这个地方返回值不是UITableViewCell类型也会导致崩溃

99、约束如何做UIView动画?

1、把需要改的约束Constraint拖条线出来,成为属性2、在需要动画的地方加入代码,改变此属性的constant属性3、开始做UIView动画,动画里边调用layoutIfNeeded方法@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTopConstraint;self.buttonTopConstraint.constant = 100;    [UIView animateWithDuration:.5 animations:^{        [self.view layoutIfNeeded];    }];

101、将tableView滚动到顶部

[tableView setContentOffset:CGPointZero animated:YES];或者[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

105、删除NSUserDefaults所有记录

//方法一  NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];    //方法二  - (void)resetDefaults {     NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];     NSDictionary * dict = [defs dictionaryRepresentation];     for (id key in dict) {          [defs removeObjectForKey:key];     }      [defs synchronize]; }// 方法三[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];

106、禁用系统滑动返回功能

- (void)viewDidAppear:(BOOL)animated{     [super viewDidAppear:animated];if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = self;    }}- (void)viewWillDisappear:(BOOL)animated {    [super viewWillDisappear:animated];    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {self.navigationController.interactivePopGestureRecognizer.delegate = nil;    }}- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{     return NO;}

107、模拟器报错

ios 生僻小技巧和总结
模拟器报错

解决办法:
打开模拟器->Simulator->Reset Content and Settings...
如果不行,就重启试试!

108、自定义cell选中背景颜色

UIView *bgColorView = [[UIView alloc] init];bgColorView.backgroundColor = [UIColor redColor];[cell setSelectedBackgroundView:bgColorView];

109、UILabel设置内边距

子类化UILabel,重写drawTextInRect方法- (void)drawTextInRect:(CGRect)rect {    // 边距,上左下右    UIEdgeInsets insets = {0, 5, 0, 5};    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];}

110、UILabel设置文字描边

子类化UILabel,重写drawTextInRect方法- (void)drawTextInRect:(CGRect)rect{    CGContextRef c = UIGraphicsGetCurrentContext();    // 设置描边宽度    CGContextSetLineWidth(c, 1);    CGContextSetLineJoin(c, kCGLineJoinRound);    CGContextSetTextDrawingMode(c, kCGTextStroke);    // 描边颜色    self.textColor = [UIColor redColor];    [super drawTextInRect:rect];    // 文本颜色    self.textColor = [UIColor yellowColor];    CGContextSetTextDrawingMode(c, kCGTextFill);    [super drawTextInRect:rect];}

112、scrollView滚动到最下边

CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);[scrollView setContentOffset:bottomOffset animated:YES];

115、为UIView某个角添加圆角

// 左上角和右下角添加圆角UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)];    CAShapeLayer *maskLayer = [CAShapeLayer layer];    maskLayer.frame = view.bounds;    maskLayer.path = maskPath.CGPath;    view.layer.mask = maskLayer;

119、让手机震动一下

倒入框架#import <AudioToolbox/AudioToolbox.h>AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);或者AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

120、layoutSubviews方法什么时候调用?

1、init方法不会调用
2、addSubview方法等时候会调用
3、bounds改变的时候调用
4、scrollView滚动的时候会调用scrollView的layoutSubviews方法(所以不建议在scrollView的layoutSubviews方法中做复杂逻辑)
5、旋转设备的时候调用
6、子视图被移除的时候调用
参考请看:http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/

121、让UILabel在指定的地方换行

// 换行符为\n,在需要换行的地方加上这个符号即可,如 label.numberOfLines = 0;label.text = @"此处\n换行";

122、摇一摇功能

1、打开摇一摇功能    [UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;2、让需要摇动的控制器成为第一响应者[self becomeFirstResponder];3、实现以下方法// 开始摇动- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event// 取消摇动- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event// 摇动结束- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

124、获取view的坐标在整个window上的位置

// v上的(0, 0)点在toView上的位置CGPoint point = [v convertPoint:CGPointMake(0, 0) toView:[UIApplication sharedApplication].windows.lastObject];或者CGPoint point = [v.superview convertPoint:v.frame.origin toView:[UIApplication sharedApplication].windows.lastObject];

126、修改UISegmentedControl的字体大小

[segment setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15.0f]} forState:UIControlStateNormal];

128、获取一个view所属的控制器

// view分类方法- (UIViewController *)belongViewController {    for (UIView *next = [self superview]; next; next = next.superview) {        UIResponder* nextResponder = [next nextResponder];        if ([nextResponder isKindOfClass:[UIViewController class]]) {            return (UIViewController *)nextResponder;        }    }    return nil;}

130、UIWebView设置背景透明

[webView setBackgroundColor:[UIColor clearColor]];[webView setOpaque:NO];

133、设置屏幕方向

 NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];[UIViewController attemptRotationToDeviceOrientation];

134、比较两个颜色是否相等

- (BOOL)isEqualToColor:(UIColor *)otherColor {    CGColorSpaceRef colorSpaceRGB = CGColorSpaceCreateDeviceRGB();    UIColor *(^convertColorToRGBSpace)(UIColor*) = ^(UIColor *color) {        if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) == kCGColorSpaceModelMonochrome) {            const CGFloat *oldComponents = CGColorGetComponents(color.CGColor);            CGFloat components[4] = {oldComponents[0], oldComponents[0], oldComponents[0], oldComponents[1]};            CGColorRef colorRef = CGColorCreate( colorSpaceRGB, components );            UIColor *color = [UIColor colorWithCGColor:colorRef];            CGColorRelease(colorRef);            return color;                    } else            return color;    };    UIColor *selfColor = convertColorToRGBSpace(self);    otherColor = convertColorToRGBSpace(otherColor);    CGColorSpaceRelease(colorSpaceRGB);    return [selfColor isEqual:otherColor];}

135、tableViewCell分割线顶到头

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {    [cell setSeparatorInset:UIEdgeInsetsZero];    [cell setLayoutMargins:UIEdgeInsetsZero];    cell.preservesSuperviewLayoutMargins = NO;}- (void)viewDidLayoutSubviews {    [self.tableView setSeparatorInset:UIEdgeInsetsZero];    [self.tableView setLayoutMargins:UIEdgeInsetsZero];}

136、不让控制器的view随着控制器的xib拉伸或压缩

self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

140、检查一个rect是否包含一个point

// point是否在rect内BOOL isContains = CGRectContainsPoint(rect, point);

141、在指定的宽度下,让UILabel自动设置最佳font

label.adjustsFontSizeToFitWidth = YES;

142、将一个image保存在相册中

UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);或者#import <Photos/Photos.h>[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{        PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];        changeRequest.creationDate          = [NSDate date];    } completionHandler:^(BOOL success, NSError *error) {        if (success) {            NSLog(@"successfully saved");        }        else {            NSLog(@"error saving to photos: %@", error);        }    }];

143、修改cell.imageView的大小

UIImage *icon = [UIImage imageNamed:@""];CGSize itemSize = CGSizeMake(30, 30);UIGraphicsBeginImageContextWithOptions(itemSize, NO ,0.0);CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);[icon drawInRect:imageRect];cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();

144、为一个view添加虚线边框

 CAShapeLayer *border = [CAShapeLayer layer];    border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;    border.fillColor = nil;    border.lineDashPattern = @[@4, @2];    border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;    border.frame = view.bounds;    [view.layer addSublayer:border];

145、UITextView中打开或禁用复制,剪切,选择,全选等功能

// 继承UITextView重写这个方法- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{// 返回NO为禁用,YES为开启    // 粘贴    if (action == @selector(paste:)) return NO;    // 剪切    if (action == @selector(cut:)) return NO;    // 复制    if (action == @selector(copy:)) return NO;    // 选择    if (action == @selector(select:)) return NO;    // 选中全部    if (action == @selector(selectAll:)) return NO;    // 删除    if (action == @selector(delete:)) return NO;    // 分享    if (action == @selector(share)) return NO;    return [super canPerformAction:action withSender:sender];}