iOS开拓中落到实处展现gif图片教程
分类:计算机编程

  • Android 的webView有回退栈,其实iOS的webView也有回退栈!
  • webView的回退栈其实就是表示webView的层级!

目录

1.给navigation Bar 设置 title 颜色
2.如何把一个CGPoint存入数组里
3.修改textField的placeholder的字体颜色、大小
4.两点之间的距离
5.使用UIScrollViewKeyboardDismissMode实现了Message app的行为
6.将color转为UIImage
7.UITableViewCell indentationLevel 使用
8.APP 屏蔽 触发事件
9.保存全屏为image
10.判断定位状态 locationServicesEnabled
11.图片缓存的清空
12.TableView Header View 跟随Tableview 滚动
13. UITabBar,移除顶部的阴影
14.ios9 crash animateWithDuration
15.KVO 监听其他类的变量
16.获取iOS设备的内网IP地址
17.UITableView回到顶部
18.webView 回退栈
19.UITableView的Group样式下顶部空白处理
20.UITableView的plain样式下,取消区头停滞效果
21.获取某个view所在的控制器
22.两种方法删除NSUserDefaults所有记录
23.取图片某一像素点的颜色 在UIImage的分类中
24.字符串反转
25.禁止锁屏
26.模态推出透明界面
27.字符串按多个符号分割
28.iOS 获取汉字的拼音
29.手动更改iOS状态栏的颜色
30.判断当前ViewController是push还是present的方式显示的
31.iOS在当前屏幕获取第一响应
32.判断对象是否遵循了某协议
33.判断view是不是指定视图的子视图
34.阿拉伯数字转中文格式
35.UIImage 占用内存大小
36.图片上绘制文字 写一个UIImage的category
37.计算文件大小
38.UIView设置部分圆角
39.取上整与取下整
40.给UIView设置图片
41.防止scrollView手势覆盖侧滑手势
42.去掉导航栏返回的back标题
43.字符串中是否含有中文
44.UITextField每四位加一个空格,实现代理
45.获取私有属性和成员变量 #import(objc/runtime.h)(由于系统原因此处用圆括号代替尖括号)
46.获取手机安装的应用
47.判断两个日期是否在同一周 写在NSDate的category里面
48.应用内打开系统设置界面
49.屏蔽触发事件,2秒后取消屏蔽
50.iOS中数字的格式化
51.获取到web view的高度
52.navigationBar变为纯透明,tobbar透明
53.navigationBar根据滑动距离的渐变色实现
54.UIWebView里面的图片自适应屏幕
55.UILable 显示html

UIWebView

iOS开发中实现显示gif图片教程,iosgif

我们知道Gif是由一阵阵画面组成的,而且每一帧画面播放的时常可能会不相等,观察上面两个例子,发现他们都没有对Gif中每一帧的显示时常做处理,这样的结果就是整个Gif中每一帧画面都是以固定的速度向前播放,很显然这并不总会符合需求。

于是自己写一个解析Gif的工具类,解决每一帧画面并遵循每一帧所对应的显示时间进行播放。

程序的思路如下:

1、首先使用ImageIO库中的CGImageSource家在Gif文件。

2、通过CGImageSource获取到Gif文件中的总的帧数,以及每一帧的显示时间。

3、通过CAKeyframeAnimation来完成Gif动画的播放。

下面直接上我写的解析和播放Gif的工具类的代码:

//

// SvGifView.h

// SvGifSample

//

// Created by maple on 3/28/13.

// Copyright (c) 2013 smileEvday. All rights reserved.

//

#import

@interface SvGifView : UIView

/*

* @brief desingated initializer

*/

- (id)initWithCenter:(CGPoint)center fileURL:(NSURL*)fileURL;

/*

* @brief start Gif Animation

*/

- (void)startGif;

/*

* @brief stop Gif Animation

*/

- (void)stopGif;

/*

* @brief get frames image(CGImageRef) in Gif

*/

  (NSArray*)framesInGif:(NSURL*)fileURL;

@end

//

// SvGifView.m

// SvGifSample

//

// Created by maple on 3/28/13.

// Copyright (c) 2013 smileEvday. All rights reserved.

//

#import "SvGifView.h"

#import

#import

/*

* @brief resolving gif information

*/

void getFrameInfo(CFURLRef url, NSMutableArray *frames, NSMutableArray *delayTimes, CGFloat *totalTime,CGFloat *gifWidth, CGFloat *gifHeight)

{

CGImageSourceRef gifSource = CGImageSourceCreateWithURL(url, NULL);

// get frame count

size_t frameCount = CGImageSourceGetCount(gifSource);

for (size_t i = 0; i < frameCount;   i) {

// get each frame

CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);

[frames addObject:(id)frame];

CGImageRelease(frame);

// get gif info with each frame

NSDictionary *dict = (NSDictionary*)CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL);

NSLog(@"kCGImagePropertyGIFDictionary %@", [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary]);

// get gif size

if (gifWidth != NULL && gifHeight != NULL) {

*gifWidth = [[dict valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];

*gifHeight = [[dict valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];

}

// kCGImagePropertyGIFDictionary中kCGImagePropertyGIFDelayTime,kCGImagePropertyGIFUnclampedDelayTime值是一样的

NSDictionary *gifDict = [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary];

[delayTimes addObject:[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime]];

if (totalTime) {

*totalTime = *totalTime   [[gifDict valueForKey:(NSString*)kCGImagePropertyGIFDelayTime] floatValue];

}

}

}

@interface SvGifView() {

NSMutableArray *_frames;

NSMutableArray *_frameDelayTimes;

CGFloat _totalTime; // seconds

CGFloat _width;

CGFloat _height;

}

@end

@implementation SvGifView

- (id)initWithCenter:(CGPoint)center fileURL:(NSURL*)fileURL;

{

self = [super initWithFrame:CGRectZero];

if (self) {

_frames = [[NSMutableArray alloc] init];

_frameDelayTimes = [[NSMutableArray alloc] init];

_width = 0;

_height = 0;

if (fileURL) {

getFrameInfo((CFURLRef)fileURL, _frames, _frameDelayTimes, &_totalTime, &_width, &_height);

}

self.frame = CGRectMake(0, 0, _width, _height);

self.center = center;

}

return self;

}

  (NSArray*)framesInGif:(NSURL *)fileURL

{

NSMutableArray *frames = [NSMutableArray arrayWithCapacity:3];

NSMutableArray *delays = [NSMutableArray arrayWithCapacity:3];

getFrameInfo((CFURLRef)fileURL, frames, delays, NULL, NULL, NULL);

return frames;

}

- (void)startGif

{

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];

NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];

CGFloat currentTime = 0;

int count = _frameDelayTimes.count;

for (int i = 0; i < count;   i) {

[times addObject:[NSNumber numberWithFloat:(currentTime / _totalTime)]];

currentTime  = [[_frameDelayTimes objectAtIndex:i] floatValue];

}

[animation setKeyTimes:times];

NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];

for (int i = 0; i < count;   i) {

[images addObject:[_frames objectAtIndex:i]];

}

[animation setValues:images];

[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];

animation.duration = _totalTime;

animation.delegate = self;

animation.repeatCount = 5;

[self.layer addAnimation:animation forKey:@"gifAnimation"];

}

- (void)stopGif

{

[self.layer removeAllAnimations];

}

// remove contents when animation end

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag

{

self.layer.contents = nil;

}

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

// Drawing code

}

@end

代码很短也比较容易,就不一一解释了。最开始的那个C函数主要就是用来解析Gif的,之所以用C函数是因为我要返回多个信息,而Objective-c只能返回一个参数,而且Objective-c和C语言可以很方便的混合编程。

另外再介绍两种使用UIImageView的方法:

  1. 使用UIWebView播放

    // 设定位置和大小

    CGRect frame = CGRectMake(50,50,0,0);

    frame.size = [UIImage imageNamed:@"guzhang.gif"].size;

    // 读取gif图片数据

    NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"guzhang" ofType:@"gif"]];

    // view生成

    UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];

    webView.userInteractionEnabled = NO;//用户不可交互

    [webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

    [self.view addSubview:webView];

    [webView release];

2.将gif图片分解成多张png图片,使用UIImageView播放。

代码如下:

UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

NSArray *gifArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"1"],

[UIImage imageNamed:@"2"],

[UIImage imageNamed:@"3"],

[UIImage imageNamed:@"4"],

[UIImage imageNamed:@"5"],

[UIImage imageNamed:@"6"],

[UIImage imageNamed:@"7"],

[UIImage imageNamed:@"8"],

[UIImage imageNamed:@"9"],

[UIImage imageNamed:@"10"],

[UIImage imageNamed:@"11"],

[UIImage imageNamed:@"12"],

[UIImage imageNamed:@"13"],

[UIImage imageNamed:@"14"],

[UIImage imageNamed:@"15"],

[UIImage imageNamed:@"16"],

[UIImage imageNamed:@"17"],

[UIImage imageNamed:@"18"],

[UIImage imageNamed:@"19"],

[UIImage imageNamed:@"20"],

[UIImage imageNamed:@"21"],

[UIImage imageNamed:@"22"],nil];

gifImageView.animationImages = gifArray; //动画图片数组

gifImageView.animationDuration = 5; //执行一次完整动画所需的时长

gifImageView.animationRepeatCount = 1; //动画重复次数

[gifImageView startAnimating];

[self.view addSubview:gifImageView];

[gifImageView release];

注意:这个方法,如果gif动画每桢间的时间间隔不同,不能达到此效果。

我们知道Gif是由一阵阵画面组成的,而且每一帧画面播放的时常可能会不相等,观察上面两个例子,发...

** iOS UIWebView 提供的接口 **

1.给navigation Bar 设置 title 颜色

UIColor *whiteColor = [UIColor whiteColor];
NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];

什么是UIWebView

// 当webView的回退栈没有数据的时候,canGoBack为NO// 也就是说,当webView的层级大于1的时候,canGoBack为YES@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;// 返回回退栈中最上层对应的webView- goBack;

2.如何把一个CGPoint存入数组里

CGPoint  itemSprite1position = CGPointMake(100, 200);
NSValue *originValue = [NSValue valueWithCGPoint:itemSprite1position];
NSMutableArray * array  = [[NSMutableArray alloc] initWithObjects:originValue, nil];
//    从数组中取值的过程是这样的:
NSValue *currentValue = [array objectAtIndex:0];
CGPoint point = [currentValue CGPointValue];

UIWebView是iOS内置的浏览器控件

** 看一下没有处理回退栈的问题 **

3.修改textField的placeholder的字体颜色、大小

法一:

self.textField.placeholder = @"username is in here!";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

法二:使用attributedString进行设置

NSString *string = @"美丽新世界";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];

    [attributedString addAttribute:NSForegroundColorAttributeName
                             value:[UIColor redColor]
                             range:NSMakeRange(0, [string length])];

    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont systemFontOfSize:16]
                             range:NSMakeRange(0, [string length])];

    self.textField.attributedPlaceholder = attributedString;

系统自带的Safari浏览器就是通过UIWebView实现的

图片 1未处理.gif

4.两点之间的距离

static __inline__ CGFloat CGPointDistanceBetweenTwoPoints(CGPoint point1, CGPoint point2) { CGFloat dx = point2.x - point1.x; CGFloat dy = point2.y - point1.y; return sqrt(dx*dx   dy*dy);}

UIWebView不但能加载远程的网页资源,还能加载绝大部分的常见文件例如:

** 处理webView的回退栈后 **

5.使用UIScrollViewKeyboardDismissMode实现了Message app的行为

像Messages app一样在滚动的时候可以让键盘消失是一种非常好的体验。现在仅仅只需要在Storyboard中改变一个简单的属性,或者增加一行代码,你的app可以和办到和Messages app一样的事情了。
这个属性使用了新的UIScrollViewKeyboardDismissMode enum枚举类型。这个enum枚举类型可能的值如下:

typedef NS_ENUM(NSInteger, UIScrollViewKeyboardDismissMode) {
    UIScrollViewKeyboardDismissModeNone,
    UIScrollViewKeyboardDismissModeOnDrag,      // dismisses the keyboard when a drag begins
    UIScrollViewKeyboardDismissModeInteractive, // the keyboard follows the dragging touch off screen, and may be pulled upward again to cancel the dismiss
} NS_ENUM_AVAILABLE_IOS(7_0);

htmlhtm

图片 2处理后.gif

6.将color转为UIImage

//将color转为UIImage
- (UIImage *)createImageWithColor:(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 *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return theImage;
}

pdf、doc、ppt、txt

** 处理webView回退栈 **

7.UITableViewCell indentationLevel 使用

UITableViewCell 属性 NSInteger indentationLevel 的使用, 对cell设置 indentationLevel的值,可以将cell 分级别。
还有 CGFloat indentationWidth; 属性,设置缩进的宽度。
总缩进的宽度: indentationLevel * indentationWidth

mp4

if ([self.webView canGoBack]) { // webView本身回退 [self.webView goBack];}else { // 原生回退 [self dismissCurrentAnimated:YES];}

8.APP 屏蔽 触发事件

[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

… …

Github demo

9.保存全屏为image

CGSize imageSize = [[UIScreen mainScreen] bounds].size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();

for (UIWindow * window in [[UIApplication sharedApplication] windows]) {
    if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, [window center].x, [window center].y);
        CGContextConcatCTM(context, [window transform]);
        CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);
        [[window layer] renderInContext:context];

        CGContextRestoreGState(context);
    }
}

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIWebView常用的加载资源的方法

10.判断定位状态 locationServicesEnabled

这个[CLLocationManager locationServicesEnabled]检测的是整个iOS系统的位置服务开关,无法检测当前应用是否被关闭。通过

CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
        [self locationManager:self.locationManager didUpdateLocations:nil];
    } else { // the user has closed this function
        [self.locationManager startUpdatingLocation];
    }
CLAuthorizationStatus来判断是否可以访问GPS
  • loadRequest:(NSURLRequest *)request;

欢迎关注我的微博:wangrui460

11.图片缓存的清空

一般使用SDWebImage 进行图片的显示和缓存,一般缓存的内容比较多了就需要进行清空缓存

清除SDWebImage的内存和硬盘时,可以同时清除session 和 cookie的缓存。

// 清理内存
[[SDImageCache sharedImageCache] clearMemory];

// 清理webview 缓存
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
    [storage deleteCookie:cookie];
}

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config.URLCache removeAllCachedResponses];
[[NSURLCache sharedURLCache] removeAllCachedResponses];

// 清理硬盘
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    [self.tableView reloadData];
}];

图片 31.png

12.TableView Header View 跟随Tableview 滚动

  • 当tableview的类型为 plain的时候,header View 就会停留在最上面。
  • 当类型为 group的时候,header view 就会跟随tableview 一起滚动了。

常用属性和方法

13. UITabBar,移除顶部的阴影

[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];
[[UITabBar appearance] setBackgroundImage:[[UIImage alloc] init]];

顶部的阴影是在UIWindow上的,所以不能简单的设置就去除。

重新加载

14.ios9 crash animateWithDuration

在iOS9 中,如果进行animateWithDuration 时,view被release 那么会引起crash。

[UIView animateWithDuration:0.25f animations:^{
        self.frame = selfFrame;
    } completion:^(BOOL finished) {
        if (finished) {
            [super removeFromSuperview];
        }
    }];
会crash。

[UIView animateWithDuration:0.25f
                          delay:0
         usingSpringWithDamping:1.0
          initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         self.frame = selfFrame;
                     } completion:^(BOOL finished) {
                         [super removeFromSuperview];
                     }];
不会Crash。

15.KVO 监听其他类的变量

[[HXSLocationManager sharedManager] addObserver:self
                                  forKeyPath:@"currentBoxEntry.boxCodeStr"
                                     options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionOld context:nil];

在实现的类self中,进行[HXSLocationManager sharedManager]类中的变量@“currentBoxEntry.boxCodeStr” 监听。

reload;

16.获取iOS设备的内网IP地址

序言:在涉及到局域网内部文件传输时,经常需要获取ios设备的内网IP地址,这里整理了一个方法可以直接获取得到ip地址串。

这里需要导入的头文件有:

#include <ifaddrs.h> 
#include <netinet/in.h>
#include <arpa/inet.h>

方法代码

  (NSString *)getDeviceIPAdress {
  NSString *address = @"an error occurred when obtaining ip address";
  struct ifaddrs *interfaces = NULL;
  struct ifaddrs *temp_addr = NULL;
  int success = 0;

  success = getifaddrs(&interfaces);

  if (success == 0) { // 0 表示获取成功
      temp_addr = interfaces;
      while (temp_addr != NULL) {
          if( temp_addr->ifa_addr->sa_family == AF_INET) {
              // 判断是否是wifi连接
              if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                  // C String 转 NSString
                  address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
              }
          }
          temp_addr = temp_addr->ifa_next;
      }
  }

  freeifaddrs(interfaces);
  return address;
}

停止加载

17.UITableView回到顶部

//***************方法一***************//
[self.tableView  scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];

//***************方法二***************//
[self.tableView setContentOffset:CGPointMake(0,0) animated:NO];

//***************方法三***************//
NSIndexPath* indexPat = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPat atScrollPosition:UITableViewScrollPositionBottom animated:YES];

18.webView 回退栈

  • webView的回退栈其实就是表示webView的层级!
  • Android 的webView有回退栈,其实iOS的webView也有回退栈!
  • iOS UIWebView 提供的接口
//  当webView的回退栈没有数据的时候,canGoBack为NO
//  也就是说,当webView的层级大于1的时候,canGoBack为YES
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
//  返回回退栈中最上层对应的webView
- (void)goBack;

处理webView回退栈

if ([self.webView canGoBack])
    {
        [self.webView goBack];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }

stopLoading;

19.UITableView的Group样式下顶部空白处理

//分组列表头部空白处理
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;

回退

20.UITableView的plain样式下,取消区头停滞效果

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = sectionHead.height;
    if (scrollView.contentOffset.y=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if(scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

21.获取某个view所在的控制器

- (UIViewController *)viewController
{
  UIViewController *viewController = nil;  
  UIResponder *next = self.nextResponder;
  while (next)
  {
    if ([next isKindOfClass:[UIViewController class]])
    {
      viewController = (UIViewController *)next;      
      break;    
    }    
    next = next.nextResponder;  
  } 
    return viewController;
}

goBack;

22.两种方法删除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];
}

前进

23.取图片某一像素点的颜色 在UIImage的分类中

- (UIColor *)colorAtPixel:(CGPoint)point
{
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point))
    {
        return nil;
    }
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = {0, 0, 0, 0};
    CGContextRef context = CGBitmapContextCreate(pixelData,
                                                 1,
                                                 1,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGContextTranslateCTM(context, -point.x, point.y - self.size.height);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), self.CGImage);
    CGContextRelease(context);

    CGFloat red   = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue  = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

24.字符串反转

第一种:
- (NSString *)reverseWordsInString:(NSString *)str
{    
    NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length];
    for (NSInteger i = str.length - 1; i >= 0 ; i --)
    {
        unichar ch = [str characterAtIndex:i];       
        [newString appendFormat:@"%c", ch];    
    }    
     return newString;
}
//第二种:
- (NSString*)reverseWordsInString:(NSString*)str
{    
     NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length];    
     [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { 
          [reverString appendString:substring];                         
      }];    
     return reverString;
}

goForward;

25.禁止锁屏

默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。

[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

需要进行检测的数据类型

26.模态推出透明界面

UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
     na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}
else
{
 self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
[self presentViewController:na animated:YES completion:nil];

@property(nonatomic)UIDataDetectorTypes dataDetectorTypes

27.字符串按多个符号分割

NSString *str = @"abc,vfr.yyuu";
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@",."];
    NSLog(@"%@",[str componentsSeparatedByCharactersInSet:set]);

是否能回退

28.iOS 获取汉字的拼音

  (NSString *)transform:(NSString *)chinese
{    
    //将NSString装换成NSMutableString 
    NSMutableString *pinyin = [chinese mutableCopy];    
    //将汉字转换为拼音(带音标)    
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);    
    NSLog(@"%@", pinyin);    
    //去掉拼音的音标    
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);    
    NSLog(@"%@", pinyin);    
    //返回最近结果    
    return pinyin;
 }

@property(nonatomic,readonly,getter=canGoBack) BOOL canGoBack;

29.手动更改iOS状态栏的颜色

- (void)setStatusBarBackgroundColor:(UIColor *)color
{
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
    {
        statusBar.backgroundColor = color;    
    }
}

是否能前进

30.判断当前ViewController是push还是present的方式显示的

NSArray *viewcontrollers=self.navigationController.viewControllers;

if (viewcontrollers.count > 1)
{
    if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self)
    {
        //push方式
       [self.navigationController popViewControllerAnimated:YES];
    }
}
else
{
    //present方式
    [self dismissViewControllerAnimated:YES completion:nil];
}
获取实际使用的LaunchImage图片
- (NSString *)getLaunchImageName
{
    CGSize viewSize = self.window.bounds.size;
    // 竖屏    
    NSString *viewOrientation = @"Portrait";  
    NSString *launchImageName = nil;    
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImageName = dict[@"UILaunchImageName"];        
        }    
    }    
    return launchImageName;
}

@property(nonatomic,readonly,getter=canGoForward) BOOL canGoForward;

31.iOS在当前屏幕获取第一响应

UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];

是否正在加载中

32.判断对象是否遵循了某协议

if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
     [self.selectedController performSelector:@selector(onTriggerRefresh)];
}

@property(nonatomic,readonly,getter=isLoading) BOOL loading;

33.判断view是不是指定视图的子视图

BOOL isView = [textView isDescendantOfView:self.view];

是否伸缩内容至适应屏幕当前尺寸

34.阿拉伯数字转中文格式

 (NSString *)translation:(NSString *)arebic
{  
    NSString *str = arebic;
    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
    NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
    NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
    NSMutableArray *sums = [NSMutableArray array];
    for (int i = 0; i ( str.length; i   ) {
        NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
        NSString *a = [dictionary objectForKey:substr];
        NSString *b = digits[str.length -i-1];
        NSString *sum = [a stringByAppendingString:b];
        if ([a isEqualToString:chinese_numerals[9]])
        {
            if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
            {
                sum = b;
                if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
                {
                    [sums removeLastObject];
                }
            }else
            {
                sum = chinese_numerals[9];
            }
            if ([[sums lastObject] isEqualToString:sum])
            {
                continue;
            }
        }

        [sums addObject:sum];
    }
    NSString *sumStr = [sums componentsJoinedByString:@""];
    NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
    NSLog(@"%@",str);
    NSLog(@"%@",chinese);
    return chinese;
}

@property(nonatomic) BOOL scalesPageToFit;

35.UIImage 占用内存大小

UIImage *image = [UIImage imageNamed:@"aa"];
NSUInteger size  = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);

监听UIWebView的加载过程

36.图片上绘制文字 写一个UIImage的category

- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
{
    //画布大小
    CGSize size=CGSizeMake(self.size.width,self.size.height);
    //创建一个基于位图的上下文
 UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO  scale:0.0
    [self drawAtPoint:CGPointMake(0.0,0.0)];

    //文字居中显示在画布上
    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
    //计算文字所占的size,文字居中显示在画布上
    CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
    //绘制文字
    [title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
    //返回绘制的新图形
    UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

成为UIWebView的代理,遵守UIWebViewDelegate协议,就能监听UIWebView的加载过程

37.计算文件大小

//文件大小
- (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:path])
    {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }

    return 0;
}

//文件夹大小
- (long long)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    long long folderSize = 0;
    if ([fileManager fileExistsAtPath:path])
    {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles)
        {
            NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
            if ([fileManager fileExistsAtPath:fileAbsolutePath])
            {
                long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize;
                folderSize  = size;
            }
        }
    }

    return folderSize;
}

开始发送请求时调用这个方法

38.UIView设置部分圆角

CGRect rect = view.bounds;
CGSize radio = CGSizeMake(30, 30);//圆角尺寸
UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//创建shapelayer
masklayer.frame = view.bounds;
masklayer.path = path.CGPath;//设置路径
view.layer.mask = masklayer;

39.取上整与取下整

floor(x),有时候也写做Floor(x),其功能是“下取整”,即取不大于x的最大整数 例如:
x=3.14,floor(x)=3
y=9.99999,floor(y)=9
与floor函数对应的是ceil函数,即上取整函数。

ceil函数的作用是求不小于给定实数的最小整数。
ceil(2)=ceil(1.2)=cei(1.5)=2.00
floor函数与ceil函数的返回值均为double型

webViewDidStartLoad:(UIWebView *)webView;

40.给UIView设置图片

UIImage *image = [UIImage imageNamed:@"image"];
self.MYView.layer.contents = (__bridge id _Nullable)(image.CGImage);
self.MYView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);

请求完毕时调用这个方法

41.防止scrollView手势覆盖侧滑手势

[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];

42.去掉导航栏返回的back标题

[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];

webViewDidFinishLoad:(UIWebView *)webView;

43.字符串中是否含有中文

  (BOOL)checkIsChinese:(NSString *)string
{
    for (int i=0; i(string.length; i  )
    {
        unichar ch = [string characterAtIndex:i];
        if (0x4E00 (= ch  && ch (= 0x9FA5)
        {
            return YES;
        }
    }
    return NO;
}

请求错误时调用这个方法

44.UITextField每四位加一个空格,实现代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // 四位加一个空格
    if ([string isEqualToString:@""])
    {
        // 删除字符
        if ((textField.text.length - 2) % 5 == 0)
        {
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
        }
        return YES;
    }
    else
    {
        if (textField.text.length % 5 == 0)
        {
            textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
        }
    }
    return YES;
}
  • webView:(UIWebView*)webView didFailLoadWithError:error;

45.获取私有属性和成员变量 #import(objc/runtime.h)(由于系统原因此处用圆括号代替尖括号)

//获取私有属性 比如设置UIDatePicker的字体颜色
- (void)setTextColor
{
    //获取所有的属性,去查看有没有对应的属性
    unsigned int count = 0;
    objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count);
    for(int i = 0;i ( count;i   )
    {
        //获得每一个属性
        objc_property_t property = propertys[i];
        //获得属性对应的nsstring
        NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        //输出打印看对应的属性
        NSLog(@"propertyname = %@",propertyName);
        if ([propertyName isEqualToString:@"textColor"])
        {
            [datePicker setValue:[UIColor whiteColor] forKey:propertyName];
        }
    }
}
//获得成员变量 比如修改UIAlertAction的按钮字体颜色
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
    for(int i =0;i ( count;i   )
    {
        Ivar ivar = ivars[i];
        NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
        NSLog(@"uialertion.ivarName = %@",ivarName);
        if ([ivarName isEqualToString:@"_titleTextColor"])
        {
            [alertOk setValue:[UIColor blueColor] forKey:@"titleTextColor"];
            [alertCancel setValue:[UIColor purpleColor] forKey:@"titleTextColor"];
        }
    }

监听UIWebView的加载过程

46.获取手机安装的应用

Class c =NSClassFromString(@"LSApplicationWorkspace");
id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
for (id item in array)
{
    NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
    //NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
    NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
    NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
}

UIWebView在发送请求之前,都会调用这个方法,如果返回NO,代表停止加载请求,返回YES,代表允许加载请求

47.判断两个日期是否在同一周 写在NSDate的category里面

- (BOOL)isSameDateWithDate:(NSDate *)date
{
    //日期间隔大于七天之间返回NO
    if (fabs([self timeIntervalSinceDate:date]) >= 7 * 24 *3600)
    {
        return NO;
    }

    NSCalendar *calender = [NSCalendar currentCalendar];
    calender.firstWeekday = 2;//设置每周第一天从周一开始
    //计算两个日期分别为这年第几周
    NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];
    NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];

    //相等就在同一周,不相等就不在同一周
    return countSelf == countDate;
}
  • webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType;

48.应用内打开系统设置界面

//iOS8之后
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//如果App没有添加权限,显示的是设定界面。如果App有添加权限(例如通知),显示的是App的设定界面。
//iOS8之前
//先添加一个url type如下图,在代码中调用如下代码,即可跳转到设置页面的对应项
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];

可选值如下:
About — prefs:root=General&path=About
Accessibility — prefs:root=General&path=ACCESSIBILITY
Airplane Mode On — prefs:root=AIRPLANE_MODE
Auto-Lock — prefs:root=General&path=AUTOLOCK
Brightness — prefs:root=Brightness
Bluetooth — prefs:root=General&path=Bluetooth
Date & Time — prefs:root=General&path=DATE_AND_TIME
FaceTime — prefs:root=FACETIME
General — prefs:root=General
Keyboard — prefs:root=General&path=Keyboard
iCloud — prefs:root=CASTLE
iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP
International — prefs:root=General&path=INTERNATIONAL
Location Services — prefs:root=LOCATION_SERVICES
Music — prefs:root=MUSIC
Music Equalizer — prefs:root=MUSIC&path=EQ
Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit
Network — prefs:root=General&path=Network
Nike   iPod — prefs:root=NIKE_PLUS_IPOD
Notes — prefs:root=NOTES
Notification — prefs:root=NOTIFICATI*****_ID
Phone — prefs:root=Phone
Photos — prefs:root=Photos
Profile — prefs:root=General&path=ManagedConfigurationList
Reset — prefs:root=General&path=Reset
Safari — prefs:root=Safari
Siri — prefs:root=General&path=Assistant
Sounds — prefs:root=Sounds
Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK
Store — prefs:root=STORE
Twitter — prefs:root=TWITTER
Usage — prefs:root=General&path=USAGE
VPN — prefs:root=General&path=Network/VPN
Wallpaper — prefs:root=Wallpaper
Wi-Fi — prefs:root=WIFI

JavaScript

49.屏蔽触发事件,2秒后取消屏蔽

[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [[UIApplication sharedApplication] endIgnoringInteractionEvents]
});

什么是JavaScript

50.iOS中数字的格式化

//通过NSNumberFormatter,同样可以设置NSNumber输出的格式。例如如下代码:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];
NSLog(@"Formatted number string:%@",string);
//输出结果为:[1223:403] Formatted number string:123,456,789

//其中NSNumberFormatter类有个属性numberStyle,它是一个枚举型,设置不同的值可以输出不同的数字格式。该枚举包括:
typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
    NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
    NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
    NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
    NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
    NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
    NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
};
//各个枚举对应输出数字格式的效果如下:其中第三项和最后一项的输出会根据系统设置的语言区域的不同而不同。
[1243:403] Formatted number string:123456789
[1243:403] Formatted number string:123,456,789
[1243:403] Formatted number string:¥123,456,789.00
[1243:403] Formatted number string:-539,222,988%
[1243:403] Formatted number string:1.23456789E8
[1243:403] Formatted number string:一亿二千三百四十五万六千七百八十九

JavaScript是一门脚本语言,简称JS

51.获取到web view的高度

CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

JS的常见作用有

52.navigationBar变为纯透明,tobbar透明

//第一种方法
//导航栏纯透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去掉导航栏底部的黑线
self.navigationBar.shadowImage = [UIImage new];
//第二种方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;

tabbar同理
[self.tabBar setBackgroundImage:[UIImage new]];
self.tabBar.shadowImage = [UIImage new];

给HTML网页添加动态功能,比如响应用户的各种操作

53.navigationBar根据滑动距离的渐变色实现

//第一种
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetToShow = 200.0;//滑动多少就完全显示
    CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;
}

//第二种
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetToShow = 200.0;
    CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;

    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
}

//生成一张纯色的图片
- (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 *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return theImage;
}

操纵HTML元素,比如添加、删除、修改网页元素

54.UIWebView里面的图片自适应屏幕

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *js = @"function imgAutoFit() { 
    var imgs = document.getElementsByTagName('img'); 
    for (var i = 0; i ( imgs.length;   i) { 
    var img = imgs[i]; 
    img.style.maxWidth = %f; 
    } 
    }";

    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];

    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
}

常见的JavaScript函数

55.UILable 显示html

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[string dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
aboutLabel.attributedText = attributedString;

alert; 弹框

document.getElementById;根据ID获得某个DOM元素

OC中调用JavaScipt

如何在OC中调用JavaScript代码

使用UIWebView的stringByEvaluatingJavaScriptFromString方法即可

****************************笔记*************************

  1. WebView的基本使用

1 概念性知识

01webView是有缺点的,会导致内存泄露,而且这个问题是它系统本身的问题。

02 手机上面的safai其实就是用webView来实现的

03 现在的开发并不完全是原生的开发,而更加倾向于原生 Html5的方式

04webView是OC代码和html代码之间进行交互的桥梁

2 代码相关

网页操控相关方法

[self.webView goBack]; 回退

[self.webView goForward]; 前进

[self.webView reload]; 刷新

设置是否能够前进和回退

self.goBackBtn.enabled = webView.canGoBack;

self.fowardBtn.enabled = webView.canGoForward;

B常用的属性设置

设置网页自动适应

self.webView.scalesPageToFit =YES;

设置检测网页中的格式类型,all表示检测所有类型包括超链接、电话号码、地址等。

self.webView.dataDetectorTypes =UIDataDetectorTypeAll;

可滚动范围

self.webView.scrollView.contentInset =UIEdgeInsetsMake(50, 0, 0, 0);

C相关代理方法

每当将加载请求的时候调用该方法,返回YES 表示加载该请求,返回NO 表示不加载该请求

可以在该方法中拦截请求

-webView:(UIWebView *)webViewshouldStartLoadWithRequest:(NSURLRequest *)requestnavigationType:(UIWebViewNavigationType)navigationType

{

return ![request.URL.absoluteStringcontainsString:@"dushu"];

}

开始加载网页,不仅监听我们指定的请求,还会监听内部发送的请求

-webViewDidStartLoad:(UIWebView *)webView

网页加载完毕之后会调用该方法

-webViewDidFinishLoad:(UIWebView *)webView

网页加载失败调用该方法

-webView:(UIWebView *)webViewdidFailLoadWithError:(NSError *)error

D其它知识点-加载本地资源

NSURL *url =[[NSBundle mainBundle] URLForResource:@"text.html"withExtension:nil];

[self.webView loadRequest:[NSURLRequestrequestWithURL:url]];

2HTML

1.Html决定网页的内容,css决定网页的样式,js决定网页的事件

2.html学习网站:

  1. OC和JS代码的互调

01 OC调用JS的代码

NSString *str = [self.webViewstringByEvaluatingJavaScriptFromString:@"sum()"];

02 JS怎么调用OC的说明

新的需求:点击按钮的时候拨打电话

但是我在点击按钮的时候,用户是不知道的,我们怎么能够知道用户点击了网页上面的一个按钮,只能通过一个技巧,那就是自己搞一个特定的协议头比如说xmg:当我拦截到你的网络请求的时候,只需要判断一下当前的协议头是不是这个就能判断你现在是否是JS调用。

OC里面有通过字符串生成SEL类型的方法,所以当拿到数据之后做下面的事情

1)截取方法的名称

2)将截取出来的字符串转换为SEL

3)利用performSelect方法来调用SEL

03 涉及到的相关方法

判断字符串是否以一个固定的字符开头,这里为A

[@"abc"hasPrefix:@"A"]

截串操作

  • (NSString*)substringFromIndex:(NSUInteger)from;

切割字符串,返回一个数组

  • (NSArray<NSString*> *)componentsSeparatedByString:(NSString *)separator;

替换操作

  • (NSString*)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString*)replacement

把string包装成SEL

SEL selector = NSSelectorFromString;

04 如何屏蔽警告

clang diagnostic push

-Warc-performSelector-leaks为唯一的警告标识,这里面的代码可以去除警告

[self performSelector:selector withObject:nil];

clang diagnostic pop

  1. NSInvocation的基本使用(任意调用对象消息方法并可以传N多参数的一个类)

在iOS中可以直接调用某个对象的消息方式有两种:

一种是performSelector:withObject;

再一种就是NSInvocation。

第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作。

封装invacation可以调用多个参数的方法

-invacation

{

1.创建一个MethodSignature,签名中保存了方法的名称,参数和返回值这个方法属于谁,那么就用谁来进行创建注意:签名一般是用来设置参数和获得返回值的,和方法的调用没有太大的关系

NSMethodSignature *signature = [ViewControllerinstanceMethodSignatureForSelector:@selector(callWithNumber:andContext:withStatus:)];

注意不要写错了方法名称

NSMethodSignature *signature = [ViewControllermethodSignatureForSelector:@selector];

2.通过MethodSignature来创建一个NSInvocationNSInvocation中保存了方法所属于的对象|方法名称|参数|返回值等等

NSInvocation *invocation = [NSInvocationinvocationWithMethodSignature:signature];

2.1

设置invocation,来调用方法

invocation.target = self;

invocation.selector

= @selector;

invocation.selector

= @selector(callWithNumber:);

invocation.selector = @selector(callWithNumber:andContext:);

invocation.selector = @selector(callWithNumber:andContext:withStatus:);

NSString

*number = @"10086";

NSString *context = @"下课了";

NSString *status = @"睡觉的时候";

注意:1.自定义的参数索引从2开始,0和1已经被self and _cmd占用了2.方法签名中保存的方法名称必须和调用的名称一致

[invocation setArgument:&number atIndex:2];

[invocation setArgument:&context atIndex:3];

[invocation setArgument:&status atIndex:4];

3.调用invok方法来执行

[invocation invoke];

}

  1. 异常处理

01 一般处理方式:

a.app异常闪退,那么捕获crash信息,并记录在本地沙盒中。

b.当下次用户重新打开app的时候,检查沙盒中是否保存有上次捕获到的crash信息。

c.如果有那么利用专门的接口发送给服务器,以求在后期版本中修复。

02 如何抛出异常

抛出异常的两种方式

@throw [NSException exceptionWithName:@"好大一个bug"reason:@"异常原因:我也不知道" userInfo:nil];

方式二

NSString*info = [NSString stringWithFormat:@"%@方法找不到",NSStringFromSelector(aSelector)];

下面这种方法是自动抛出的

[NSExceptionraise:@"这是一个异常" format:info,nil];

03 如何捕获异常

NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);

void UncaughtExceptionHandler(NSException*exception) {

NSArray *arr = [exception callStackSymbols];得到当前调用栈信息

NSString *reason = [exception reason];非常重要,就是崩溃的原因

NSString *name = [exception name];异常类型

NSString *errorMsg = [NSString stringWithFormat:@"当前调用栈的信息:%@nCrash的原因:%@n异常类型:%@n",arr,reason,name];

把该信息保存到本地沙盒,下次回传给服务器。

}

void UncaughtExceptionHandler(NSException *exception) {

获取异常崩溃信息

NSArray *callStack = [exceptioncallStackSymbols];

NSString *reason = [exceptionreason];

NSString *name = [exceptionname];

NSString*content = [NSString stringWithFormat:@"========异常错误报告========nname:%@nreason:n%@ncallStackSymbols:n%@",name,reason,[callStack componentsJoinedByString:@"n"]];把异常崩溃信息发送至开发者邮件NSMutableString*mailUrl = [NSMutableString

string];

[mailUrl appendString:@"mailto:test@qq.com"];[mailUrl appendString:@"?subject=程序异常崩溃,请配合发送异常报告,谢谢合作!"];[mailUrl

appendFormat:@"&body=%@",content];

 打开地址NSString*mailPath = [mailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];[[UIApplication

sharedApplication] openURL:[NSURL URLWithString:mailPath]];

}

补充

关于JS相关的学习框架:WebViewJavascriptBridge

本文由pc28.am发布于计算机编程,转载请注明出处:iOS开拓中落到实处展现gif图片教程

上一篇:无标题文章,1环境下上架iOS 下一篇:没有了
猜你喜欢
热门排行
精彩图文