链接:http://www.jianshu.com/p/9fcd37c0ea05
7、播放一张张连续的图片
// 加入现在有三张图片分别为animate_1、animate_2、animate_3
// 方法一
imageView.animationImages = @[[UIImage imageNamed:@"animate_1"], [UIImage imageNamed:@"animate_2"], [UIImage imageNamed:@"animate_3"]];
imageView.animationDuration = 1.0;
// 方法二
imageView.image = [UIImage animatedImageNamed:@"animate_" duration:1.0];
// 方法二解释下,这个方法会加载animate_为前缀的,后边0-1024,也就是animate_0、animate_1一直到animate_1024
8、加载gif图片
推荐使用这个框架 FLAnimatedImage
9、防止离屏渲染为image添加圆角
// image分类
- (UIImage *)circleImage
{
// NO代表透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);
// 获得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加一个圆
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
// 方形变圆形
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 将图片画上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
16、将一个view保存为pdf格式
- (void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[aView.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}
20、键盘上方增加工具栏
UIToolbar *keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered target:self
action:@selector(doneClicked:)];
[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];
txtField.inputAccessoryView = keyboardDoneButtonView;
21、copy一个view
因为UIView没有实现copy协议,因此找不到copyWithZone方法,使用copy的时候导致崩溃
但是我们可以通过归档再解档实现copy,这相当于对视图进行了一次深拷贝,代码如下
id copyOfView =
[NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:originalView]];
22、在image上绘制文字并生成新的image
UIFont *font = [UIFont boldSystemFontOfSize:12];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
CGRect rect = CGRectMake(point.x, point.y, image.size.width, image.size.height);
[[UIColor whiteColor] set];
[text drawInRect:CGRectIntegral(rect) withFont:font];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
23、判断一个view是否为另一个view的子视图
// 如果myView是self.view本身,也会返回yes
BOOL isSubView = [myView isDescendantOfView:self.view];
25、UICollectionView自动滚动到某行
// 重写viewDidLayoutSubviews方法
-(void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
}
27、判断某一行的cell是否已经显示
CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);
29、动画修改label上的文字
// 方法一
CATransition *animation = [CATransition animation];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = kCATransitionFade;
animation.duration = 0.75;
[self.label.layer addAnimation:animation forKey:@"kCATransitionFade"];
self.label.text = @"New";
// 方法二
[UIView transitionWithView:self.label
duration:0.25f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.label.text = @"Well done!";
} completion:nil];
// 方法三
[UIView animateWithDuration:1.0
animations:^{
self.label.alpha = 0.0f;
self.label.text = @"newText";
self.label.alpha = 1.0f;
}];
32、设置UIImage的透明度
// 方法一、添加UIImage分类
- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextSetAlpha(ctx, alpha);
CGContextDrawImage(ctx, area, self.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
// 方法二、如果没有奇葩需求,干脆用UIImageView设置透明度
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"yourImage"]];
imageView.alpha = 0.5;
33、Attempt to mutate immutable object with insertString:atIndex:
这个错是因为你拿字符串调用insertString:atIndex:方法的时候,调用对象不是NSMutableString,应该先转成这个类型再调用
34、UIWebView添加单击手势不响应
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webViewClick)];
tap.delegate = self;
[_webView addGestureRecognizer:tap];
// 因为webView本身有一个单击手势,所以再添加会造成手势冲突,从而不响应。需要绑定手势代理,并实现下边的代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
38、在UITextView中显示html文本
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 30, 100, 199)];
textView.backgroundColor = [UIColor redColor];
[self.view addSubview:textView];
NSString *htmlString = @"<h1>Header</h1><h2>Subheader</h2><p>Some <em>text</em></p>![](http://blogs.babble.com/famecrawler/files/2010/11/mickey_mouse-1097.jpg)";
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes: nil error: nil];
textView.attributedText = attributedString;
39、监听scrollView是否滚动到了顶部/底部
-(void)scrollViewDidScroll: (UIScrollView*)scrollView
{
float scrollViewHeight = scrollView.frame.size.height;
float scrollContentSizeHeight = scrollView.contentSize.height;
float scrollOffset = scrollView.contentOffset.y;
if (scrollOffset == 0)
{
// 滚动到了顶部
}
else if (scrollOffset + scrollViewHeight == scrollContentSizeHeight)
{
// 滚动到了底部
}
}
41、选中textField或者textView所有文本(我这里以textView为例)
[self.textView setSelectedTextRange:[self.textView textRangeFromPosition:self.textView.beginningOfDocument toPosition:self.textView.endOfDocument]]
42、从导航控制器中删除某个控制器
// 方法一、知道这个控制器所处的导航控制器下标
NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
[navigationArray removeObjectAtIndex: 2];
self.navigationController.viewControllers = navigationArray;
// 方法二、知道具体是哪个控制器
NSArray* tempVCA = [self.navigationController viewControllers];
for(UIViewController *tempVC in tempVCA)
{
if([tempVC isKindOfClass:[urViewControllerClass class]])
{
[tempVC removeFromParentViewController];
}
}
43、隐藏UITextView/UITextField光标
textField.tintColor = [UIColor clearColor];
44、当UITextView/UITextField中没有文字时,禁用回车键
textField.enablesReturnKeyAutomatically = YES;
48、仿苹果抖动动画
#define RADIANS(degrees) (((degrees) * M_PI) / 180.0)
- (void)startAnimate {
view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-5));
[UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse) animations:^ {
view.transform = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(5));
} completion:nil];
}
- (void)stopAnimate {
[UIView animateWithDuration:0.25 delay:0.0 options:(UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear) animations:^ {
view.transform = CGAffineTransformIdentity;
} completion:nil];
}
49、修改UISearBar内部背景颜色
UITextField *textField = [_searchBar valueForKey:@"_searchField"];
textField.backgroundColor = [UIColor redColor];
50、UITextView滚动到顶部
// 方法一
[self.textView scrollRangeToVisible:NSMakeRange(0, 0)];
// 方法二
[self.textView setContentOffset:CGPointZero animated:YES];
53、UITextField文字周围增加边距
// 子类化UITextField,增加insert属性
@interface WZBTextField : UITextField
@property (nonatomic, assign) UIEdgeInsets insets;
@end
// 在.m文件重写下列方法
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);
if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {
return [self adjustRectWithWidthRightView:paddedRect];
}
return paddedRect;
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);
if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {
return [self adjustRectWithWidthRightView:paddedRect];
}
return paddedRect;
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);
if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeWhileEditing) {
return [self adjustRectWithWidthRightView:paddedRect];
}
return paddedRect;
}
- (CGRect)adjustRectWithWidthRightView:(CGRect)bounds {
CGRect paddedRect = bounds;
paddedRect.size.width -= CGRectGetWidth(self.rightView.frame);
return paddedRect;
}
54、监听UISlider拖动状态
// 添加事件
[slider addTarget:self action:@selector(sliderValurChanged:forEvent:) forControlEvents:UIControlEventValueChanged];
// 实现方法
- (void)sliderValurChanged:(UISlider*)slider forEvent:(UIEvent*)event {
UITouch *touchEvent = [[event allTouches] anyObject];
switch (touchEvent.phase) {
case UITouchPhaseBegan:
NSLog(@"开始拖动");
break;
case UITouchPhaseMoved:
NSLog(@"正在拖动");
break;
case UITouchPhaseEnded:
NSLog(@"结束拖动");
break;
default:
break;
}
}
55、设置UITextField光标位置
// textField需要设置的textField,index要设置的光标位置
- (void)cursorLocation:(UITextField *)textField index:(NSInteger)index
{
NSRange range = NSMakeRange(index, 0);
UITextPosition *start = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location];
UITextPosition *end = [textField positionFromPosition:start offset:range.length];
[textField setSelectedTextRange:[textField textRangeFromPosition:start toPosition:end]];
}
56、去除webView底部黑色
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
for (UIView *v1 in [webView subviews])
{
if ([v1 isKindOfClass:[UIScrollView class]])
{
for (UIView *v2 in v1.subviews)
{
if ([v2 isKindOfClass:[UIImageView class]])
{
v2.hidden = YES;
}
}
}
}
57、获取collectionViewCell在屏幕中的frame
UICollectionViewLayoutAttributes *attributes = [collectionView layoutAttributesForItemAtIndexPath:indexPath];
CGRect cellRect = attributes.frame;
CGRect cellFrameInSuperview = [collectionView convertRect:cellRect toView:[cv superview]];
59、解决当UIScrollView上有UIButton的时候,触摸到button滑动不了的问题
// 子类化UIScrollView,并重写以下方法
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.delaysContentTouches = NO;
}
return self;
}
- (BOOL)touchesShouldCancelInContentView:(UIView *)view {
if ([view isKindOfClass:UIButton.class]) {
return YES;
}
return [super touchesShouldCancelInContentView:view];
}
60、UITextView中的文字添加阴影效果
- (void)setTextLayer:(UITextView *)textView color:(UIColor *)color
{
CALayer *textLayer = ((CALayer *)[textView.layer.sublayers objectAtIndex:0]);
textLayer.shadowColor = color.CGColor;
textLayer.shadowOffset = CGSizeMake(0.0f, 1.0f);
textLayer.shadowOpacity = 1.0f;
textLayer.shadowRadius = 1.0f;
}
66、解决openUrl延时问题
// 方法一
dispatch_async(dispatch_get_main_queue(), ^{
UIApplication *application = [UIApplication sharedApplication];
if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
[application openURL:URL options:@{}
completionHandler:nil];
} else {
[application openURL:URL];
}
});
// 方法二
[self performSelector:@selector(redirectToURL:) withObject:url afterDelay:0.1];
- (void) redirectToURL
{
UIApplication *application = [UIApplication sharedApplication];
if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
[application openURL:URL options:@{}
completionHandler:nil];
} else {
[application openURL:URL];
}
}
67、页面跳转实现翻转动画
// modal方式
TestViewController *vc = [[TestViewController alloc] init];
vc.view.backgroundColor = [UIColor redColor];
vc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:vc animated:YES completion:nil];
// push方式
TestViewController *vc = [[TestViewController alloc] init];
vc.view.backgroundColor = [UIColor redColor];
[UIView beginAnimations:@"View Flip" context:nil];
[UIView setAnimationDuration:0.80];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO];
[self.navigationController pushViewController:vc animated:YES];
[UIView commitAnimations];
68、tableView实现无限滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat actualPosition = scrollView.contentOffset.y;
CGFloat contentHeight = scrollView.contentSize.height - scrollView.frame.size.height;
if (actualPosition >= contentHeight) {
[self.dataArr addObjectsFromArray:self.dataArr];
[self.tableView reloadData];
}
}
69、代码方式调整屏幕亮度
// brightness属性值在0-1之间,0代表最小亮度,1代表最大亮度
[[UIScreen mainScreen] setBrightness:0.5];
72、删除UISearchBar系统默认边框
// 方法一
searchBar.searchBarStyle = UISearchBarStyleMinimal;
// 方法二
[searchBar setBackgroundImage:[[UIImage alloc]init]];
// 方法三
searchBar.barTintColor = [UIColor whiteColor];
73、为UICollectionViewCell设置圆角和阴影
cell.contentView.layer.cornerRadius = 2.0f;
cell.contentView.layer.borderWidth = 1.0f;
cell.contentView.layer.borderColor = [UIColor clearColor].CGColor;
cell.contentView.layer.masksToBounds = YES;
cell.layer.shadowColor = [UIColor lightGrayColor].CGColor;
cell.layer.shadowOffset = CGSizeMake(0, 2.0f);
cell.layer.shadowRadius = 2.0f;
cell.layer.shadowOpacity = 1.0f;
cell.layer.masksToBounds = NO;
cell.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds cornerRadius:cell.contentView.layer.cornerRadius].CGPath;
74、让正在滑动的scrollView停止滚动(不是禁止,而是暂时停止滚动)
[scrollView setContentOffset:scrollView.contentOffset animated:NO];
77、如何防止添加多个NSNotification观察者?
// 解决方案就是添加观察者之前先移除下这个观察者
[[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object];
[[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object];
78、将一个xib添加到另外一个xib上
// 假设你的自定义view名字为CustomView,你需要在CustomView.m中重写 `- (instancetype)initWithCoder:(NSCoder *)aDecoder` 方法,代码如下:
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
[self addSubview:[[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0]];
}
return self;
}
将一个xib添加到另外一个xib上.png
81、获取字符串中的数字
- (NSString *)getNumberFromStr:(NSString *)str
{
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return [[str componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:@""];
}
NSLog(@"%@", [self getNumberFromStr:@"a0b0c1d2e3f4fda8fa8fad9fsad23"]); // 00123488923
82、为UIView的某个方向添加边框
// 添加UIView分类
// UIView+WZB.h
#import <UIKit/UIKit.h>
/**
边框方向
- WZBBorderDirectionTop: 顶部
- WZBBorderDirectionLeft: 左边
- WZBBorderDirectionBottom: 底部
- WZBBorderDirectionRight: 右边
*/
typedef NS_ENUM(NSInteger, WZBBorderDirectionType) {
WZBBorderDirectionTop = 0,
WZBBorderDirectionLeft,
WZBBorderDirectionBottom,
WZBBorderDirectionRight
};
@interface UIView (WZB)
/**
为UIView的某个方向添加边框
@param direction 边框方向
@param color 边框颜色
@param width 边框宽度
*/
- (void)wzb_addBorder:(WZBBorderDirectionType)direction color:(UIColor *)color width:(CGFloat)width;
@end
// UIView+WZB.m
#import "UIView+WZB.h"
@implementation UIView (WZB)
- (void)wzb_addBorder:(WZBBorderDirectionType)direction color:(UIColor *)color width:(CGFloat)width
{
CALayer *border = [CALayer layer];
border.backgroundColor = color.CGColor;
switch (direction) {
case WZBBorderDirectionTop:
{
border.frame = CGRectMake(0.0f, 0.0f, self.bounds.size.width, width);
}
break;
case WZBBorderDirectionLeft:
{
border.frame = CGRectMake(0.0f, 0.0f, width, self.bounds.size.height);
}
break;
case WZBBorderDirectionBottom:
{
border.frame = CGRectMake(0.0f, self.bounds.size.height - width, self.bounds.size.width, width);
}
break;
case WZBBorderDirectionRight:
{
border.frame = CGRectMake(self.bounds.size.width - width, 0, width, self.bounds.size.height);
}
break;
default:
break;
}
[self.layer addSublayer:border];
}
83、通过属性设置UISwitch、UIProgressView等控件的宽高
mySwitch.transform = CGAffineTransformMakeScale(5.0f, 5.0f);
progressView.transform = CGAffineTransformMakeScale(5.0f, 5.0f);
84、自动搜索功能,用户连续输入的时候不搜索,用户停止输入的时候自动搜索(我这里设置的是0.5s,可根据需求更改)
// 输入框文字改变的时候调用
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
// 先取消调用搜索方法
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchNewResult) object:nil];
// 0.5秒后调用搜索方法
[self performSelector:@selector(searchNewResult) withObject:nil afterDelay:0.5];
}
85、修改UISearchBar的占位文字颜色
// 方法一(推荐使用)
UITextField *searchField = [searchBar valueForKey:@"_searchField"];
[searchField setValue:[UIColor blueColor] forKeyPath:@"_placeholderLabel.textColor"];
86、某个界面多个事件同时响应引起的问题(比如,两个button同时按push到新界面,两个都会响应,可能导致push重叠)
// UIView有个属性叫做exclusiveTouch,设置为YES后,其响应事件会和其他view互斥(有其他view事件响应的时候点击它不起作用)
view.exclusiveTouch = YES;
// 一个一个设置太麻烦了,可以全局设置
[[UIView appearance] setExclusiveTouch:YES];
// 或者只设置button
[[UIButton appearance] setExclusiveTouch:YES];
87、修改tabBar的frame
// 子类化UITabBarViewController,我这里以修改tabBar高度为例,重写viewWillLayoutSubviews方法
#import "WZBTabBarViewController.h"
@interface WZBTabBarViewController ()
@end
@implementation WZBTabBarViewController
- (void)viewWillLayoutSubviews {
CGRect tabFrame = self.tabBar.frame;
tabFrame.size.height = 100;
tabFrame.origin.y = self.view.frame.size.height - 100;
self.tabBar.frame = tabFrame;
}
@end
88、修改键盘背景颜色
// 设置某个键盘颜色
textField.keyboardAppearance = UIKeyboardAppearanceAlert;
// 设置工程中所有键盘颜色
[[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceAlert];
92、设置UIButton高亮时的背景颜色
// 方法一、子类化UIButton,重写setHighlighted:方法,代码如下
#import "WZBButton.h"
@implementation WZBButton
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
UIColor *normalColor = [UIColor greenColor];
UIColor *highlightedColor = [UIColor redColor];
self.backgroundColor = highlighted ? highlightedColor : normalColor;
}
// 方法二、利用setBackgroundImage:forState:方法
[button setBackgroundImage:[self imageWithColor:[UIColor blueColor]] forState:UIControlStateHighlighted];
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
93、关于图片拉伸
推荐看这个博客,讲的很详细
96、让push跳转动画像modal跳转动画那样效果(从下往上推上来)
- (void)push
{
TestViewController *vc = [[TestViewController alloc] init];
vc.view.backgroundColor = [UIColor redColor];
CATransition* transition = [CATransition animation];
transition.duration = 0.4f;
transition.type = kCATransitionMoveIn;
transition.subtype = kCATransitionFromTop;
[self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[self.navigationController pushViewController:vc animated:NO];
}
- (void)pop
{
CATransition* transition = [CATransition animation];
transition.duration = 0.4f;
transition.type = kCATransitionReveal;
transition.subtype = kCATransitionFromBottom;
[self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[self.navigationController popViewControllerAnimated:NO];
}
97、上传图片太大,压缩图片
-(UIImage *)resizeImage:(UIImage *)image
{
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = 300.0;
float maxWidth = 400.0;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.5;//50 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth)
{
if(imgRatio < maxRatio)
{
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio)
{
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else
{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}