AFNetworking

下载AFNetworking开源代码

点击链接:AFNetworking

Architecture


NSURLConnection

  • AFURLConnectioinOperatioin
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager

NSURLSession(iOS 7 /Mac OS 10.9)

  • AFURLSessionManager
  • AFHTTPSessionManager

Serialization

  • AFURLRequestSerialization

    • AFHTTPRequestSerialization

    • AFJSONRequestSerialization

    • AFPropertyListRequestSerialization

  • AFURLResponseSerialization

    • AFHTTPResponseSerialization

    • AFJSONResponseSerialization

    • AFXMLParserResponseSerialization

    • AFXMLDocumentResponseSerialization (MAC OS X)

    • AFPropertyListResponseSerialization

    • AFImageResponseSerializer

    • AFCompoundResponseSerializer

Additional Functionality

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

Usage

#define kBaseURL @”http://afnetworking.sinaapp.com


1
2
3
requestSerializer 默认是 [AFHTTPRequestSerializer serializer];
responseSerializer 默认是 [AFJSONResponseSerializer serializer];

AFHTTPRequestOperation

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_get.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:urlStr parameters:parameters error:nil];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc]initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
-----------------------------------------------------    
结果:
    Success:
    response object : {
        data =     {
            foo = bar;
        };
        success = 1;
    }
    Error:{
            "errors":"Parameter error!",
            "success":false
    }
-----------------------------------------------------    

AFHTTPRequestOperationManager

GET Request

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_get.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
-----------------------------------------------------    
结果:
    Success: 
    response object : {
        data =     {
            foo = bar;
        };
        success = 1;
    }
    Error:{
            "errors":"Parameter error!",
            "success":false
    }
-----------------------------------------------------        

POST URL-Form-Request

NSString *httpUrlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_http.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:httpUrlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];

NSString *jsonUrlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_json.json"];
[manager POST:jsonUrlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
-----------------------------------------------------    
结果:
    Success: 
    response object : {
        data =     {
            foo = bar;
        };
        success = 1;
    }
    Error:{
            "errors":"Parameter error!",
            "success":false
    }
-----------------------------------------------------

POST Multi-Part-Request

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"upload2server.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"b_Aquarius" withExtension:@"jpg"];
    [formData appendPartWithFileURL:fileURL name:@"image" fileName:@"constellation.jpg" mimeType:@"image/jpeg" error:nil];
    fileURL = [[NSBundle mainBundle] URLForResource:@"b_Aries" withExtension:@"png"];
    [formData appendPartWithFileURL:fileURL name:@"image" fileName:@"constellation.png" mimeType:@"image/png" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response object : %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error : %@",error);
}];
-----------------------------------------------------
结果:
    Success: 
    Response object : {
        data =     (
                    {
                name = "constellation.jpg";
                url = "http://afnetworking-userdomain.stor.sinaapp.com/constellation.jpg";
            },
                    {
                name = "constellation.png";
                url = "http://afnetworking-userdomain.stor.sinaapp.com/constellation.png";
            }
        );
        success = 1;
    }
-----------------------------------------------------

AFURLSessionManager

Creating a Download Task

/#define kDownloadUrl @”http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/346495/3464861417179661128.mp3?xcode=91aea20a92711d3d83f3f76a0952eb4b63b77ba183a87289&song_id=346486kDownloadUrl 是下载链接

NSURL *url = [NSURL URLWithString:kDownloadUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSString *filePath = @"/Users/qingyun/Desktop";
    NSString *newFielPath = [filePath stringByAppendingPathComponent:response.suggestedFilename];
    NSLog(@"name : %@",response.suggestedFilename);
    return [NSURL fileURLWithPath:newFielPath];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"File path : %@",filePath);
    }
}];
[downloadTask resume];
-----------------------------------------------------
结果:
Success: File path : file:///Users/qingyun/Desktop/Only%20Love.mp3
-----------------------------------------------------

Creation a Upload Task

    NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"upload2server.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
NSString *filePath = @"file:///Users/qingyun/Desktop/xml&json.pdf";
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:filePath] progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"Response objecct : %@",responseObject);
    }
}];
[uploadTask resume];
-----------------------------------------------------    
结果:
  Success:Response objecct : {
success = 1;
}
-----------------------------------------------------

Creation a Upload Task For Multi-Part Request, With Progress

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"upload2server.json"];
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"b_Cancer" withExtension:@"png"];
    [formData appendPartWithFileURL:fileURL name:@"image" fileName:@"Cancer.png" mimeType:@"image/png" error:nil];

    fileURL = [NSURL URLWithString:@"file://Users/qingyun/Desktop/xml&json.pdf"];
    [formData appendPartWithFileURL:fileURL name:@"image" error:nil];
} error:nil];
NSProgress *progress = nil;
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"Response objecct : %@",responseObject);
    }
}];
[uploadTask resume];
-----------------------------------------------------    
结果:
Success:Response objecct : {
        data =     (
                    {
                name = "Cancer.png";
                url = "http://afnetworking-userdomain.stor.sinaapp.com/Cancer.png";
            }
        );
        success = 1;
    }
-----------------------------------------------------

Creation a Data Task

NSURL *url = [NSURL URLWithString:[kBaseURL stringByAppendingPathComponent:@"response.json"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error : %@",error);
    }else{
        NSLog(@"response object : %@",responseObject);
    }
}];
[dataTask resume];
-----------------------------------------------------
结果:
Success: response object : {
data = "This is a json data.";
success = 1;
}
-----------------------------------------------------

AFHTTPSessionManager

GET Request

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_get.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDataTask *dataTask = [manager GET:urlStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error : %@",error);
}];
[dataTask resume];
----------------------------------------------------
结果:
Success :response object : {
    data =     {
        foo = bar;
    };
    success = 1;
}
----------------------------------------------------

POSTRequest

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_http.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDataTask *dataTask = [manager POST:urlStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"response object : %@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error : %@",error);
}];
[dataTask resume];
-----------------------------------------------------
结果:
Success:response object : {
    data =     {
        foo = bar;
    };
    success = 1;
}
-----------------------------------------------------

HEADRequest

NSString *urlStr = [kBaseURL stringByAppendingPathComponent:@"request_post_body_http.json"];
NSDictionary *parameters = @{@"foo":@"bar"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSURLSessionDataTask *dataTask = [manager HEAD:urlStr parameters:parameters success:^(NSURLSessionDataTask *task) {
    NSLog(@"Task : %@",task);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Task : %@ Error : %@",task,error);
}];
[dataTask resume];
----------------------------------------------------
结果:
Success: Task : <__NSCFLocalDataTask: 0x8d77b10> { completed }
----------------------------------------------------

AFNetworkReachabilityManager

/*
 *AFNetworkReachabilityStatusNotReachable     = 0,
 *AFNetworkReachabilityStatusReachableViaWWAN = 1,
 *AFNetworkReachabilityStatusReachableViaWiFi = 2
 */
NSArray *array = @[@"不可达",@"2G/3G/4G",@"wi-fi"];

[AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[self.manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"网络检测" message:[NSString stringWithFormat:@"%@",array[status]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];

}];

-----
[manager startMonitoring];
[manager stopMonitoring];

XML_JSON

XML

SAX解析

  1. 创建XML解析对象
1
2
NSURL *url = [NSBundle mainBundle] URLForResource:@"bookstore" withExternsion:@"xml"];
NSXMLParser *parser = [][NSXMLParser alloc]initWithContentsOfURL:url];
  1. 设置XMLParser 对象的delegate
1
parser.delegate = self;
  1. 调用delegate的fangf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//当时开始解析的时候条用该方法,通常在这个方法里, 创建模型数组
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
//当开始解析,遇到元素的开始标签时,回调用这个方法,通常在这个方法里,创建模型对象,或解析标签中得属性并保存在模型对象中
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//当解析到xml标签的文本内容时,回调用这个方法,通常在这个方法里,暂存解析到的文本内容
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//当解析xml内容遇到结束标签时,回调用这个方法,通常在这个方法里,需要将模型对象保存到数组中或把标签对应的文本内容解析出来,保存在模型对象中。(通过KVC赋值)
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
//当整个xml解析完成条用这个方法,可以完成其他操作
}

DOM解析

以下以GDataXMLNode为例:

1
2
3
4
5
6
7
8
9
* <节点> (GDataXMLNode)
* 根据 DOM,XML ⽂文档中的每个成分都是⼀一个节点。
* DOM 是这样规定的:
* 整个⽂文档是⼀一个⽂文档节点
* 每个 XML 标签是⼀一个元素节点
* 包含在 XML 元素中的⽂文本是⽂文本节点
* 每⼀一个 XML 属性是⼀一个属性节点
* 注释属于注释节点

  1. 导入第三方库
1
2
3
4
5
导入第三方库时,首先编译检查是否可用,(头文件是否编译通过,头文件是否需要导入头文件路径,是否使用非ARC环境)
1. 头文件编译未通过,添加文件搜索路径,头文件为系统头文件时:在Build setting下的Header Search Paths 添加/usr/include/libxml2
头文件为用户头文件时:在Build setting下的User Header Search Paths 添加/usr/include/libxml2
2. 在Build Phases 下的Link Binary With Libraries 添加libxml2.dylib,链接的动态库
3. 在Build Phases 下的Compile Sources 将导入的编译文件设置为非ARC 即添加 -fno-objc-arc即可
  1. 创建GDataXMLDocument对象
1
2
NSData *data = [[NSBundle mainBundle] URLForResource:@"bokstore" withExternsion:"xml"];
GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithData:data options:0 error:nil];
  1. 获取根元素rootElement
1
[document rootElement];
  1. 由根元素,可以获取到根元素下的子元素,以及对子元素的属性赋值;
1
2
3
4
5
6
获取子元素的方法:
- (NSArray *)elementsForName:(NSString *)name;
获取子元素属性的方法:
- (GDataXMLNode *)attributeForName:(NSString *)name;
将GDataXMLNode对象转换为NSString对象的方法:
- (NSString *)stringValue;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
for (GDataXMLElement *element in elements) {
// 创建图书对象
YMBook *book = [[YMBook alloc] init];
// 根据属性名字,解析book元素的属性值
book.category = [[element attributeForName:kCategory]
stringValue];
// 解析book的⼦子元素包含的⽂文本内容及其⼦子元素的属性
[0];
GDataXMLElement *titleElement = [element elementsForName:kTitle]
book.title = [titleElement stringValue];
book.lang = [[titleElement attributeForName:kLanguage]
stringValue];
GDataXMLElement *authorElement = [element
elementsForName:kAuthor][0];
book.author = [authorElement stringValue];
GDataXMLElement *yearElement = [element elementsForName:kYear]
[0];
book.year = [yearElement stringValue];
GDataXMLElement *priceElement = [element elementsForName:kPrice]
[0];
book.price = [priceElement stringValue];
 [_bookStore addObject:book];
}

JSON

1.数据分类
从结构上看,所有的数据(data)最终都可以分解成三种类型:

    - 第一种类型是标量(scalar),也就是一个单独的字符串(string)或数字 (numbers),比如"北京"这个单独的词 

    - 第二种类型是序列(sequence),也就是若干个相关的数据按照一定顺序并列在一 起,又叫做数组(array)或列表(List),比如"北京,上海" 

    - 第三种类型是映射(mapping),也就是一个名/值对(Name/value),即数据有一个 名称,还有一个与之相对应的值,这又称作散列(hash)或字典(dictionary),比 如"首都:北京"

Douglas Crockford发明了JSON,Json的规定非常简单:

  1. 并列的数据之间用逗号(“, “)分隔

  2. 映射用冒号(“: “)表示

  3. 并列数据的集合(数组)用方括号(“[]”)表示

  4. 映射的集合(对象)用大括号(“{}”)表示

比如,下面这句话:

“”北京市的⾯面积为16800平⽅方公⾥里,常住⼈人⼜⼝口1600万⼈人。上海市的⾯面积为6400平⽅方 公⾥里,常住⼈人⼜⼝口1800万。”

写成JSON格式就是这样:

1
2
3
4
[
 {"城市":"北京","⾯面积":16800,"⼈人⼝口":1600},
 {"城市":"上海","⾯面积
]

如果事先知道数据的结构,上面的写法还可以进一步简化:

1
2
3
4
[
["北京",16800,1600],
["上海",6400,1800]
]

NSJSONSerialization

1
2
3
4
5
6
7
8
9
10
- 反序列
+ (id)JSONObjectWithData:(NSData *)data
error:(NSError **)error
options:(NSJSONReadingOptions)opt
error:(NSError **)error
- 序列化
+ (NSData *)dataWithJSONObject:(id)obj
options:(NSJSONWritingOptions)opt


JSONKit

  1. 需要导入第三方库

使用: -fno-objc-arc

序列化: NSArray NSDictionary NSString

1
2
3
4
5
6
7
8
9
10
11
12
JSONData
– JSONDataWithOptions:includeQuotes:error:
-
JSONDataWithOptions:serializeUnsupportedClassesUsingDelegate:selector:error:
- JSONDataWithOptions:serializeUnsupportedClassesUsingBlock:error:
– JSONString
– JSONStringWithOptions:includeQuotes:error:
-
JSONStringWithOptions:serializeUnsupportedClassesUsingDelegate:selector:erro
r:
– JSONStringWithOptions:serializeUnsupportedClassesUsingBlock:error:

反序列化:NSData NSString

1
2
3
4
5
6
7
8
9
10
11
12
13
– objectFromJSONData
– objectFromJSONDataWithParseOptions:
– objectFromJSONDataWithParseOptions:error:
– mutableObjectFromJSONData
– mutableObjectFromJSONDataWithParseOptions:
– mutableObjectFromJSONDataWithParseOptions:error:
– objectFromJSONString
– objectFromJSONStringWithParseOptions:
– objectFromJSONStringWithParseOptions:error:
– mutableObjectFromJSONString
– mutableObjectFromJSONStringWithParseOptions:
– mutableObjectFromJSONStringWithParseOptions:error:


UIScrollView

ScrollView 不能滑动的常见原因

  1. contentsize 未设置
  2. scrollEnabled = NO;
  3. userInteractionEnabled = NO;
  4. 未取消autolayout

contentInset属性

控制scrollView四周可以多出的滑动长度,默认为四个参数均为0,急不可以滑动超出contentSize以外的区域

-(UIView )viewForZoomingInScrollView:(UIScrollView )scrollView;

该方法实现对返回的视图进行缩放大小,放回的视图必须是scrollView的子视图

diractionalLockEnabled

该属性设置为YES时可以控制在滑动scrollView时不会有晃动的效果,即当用户的滑动的方向不是正方向时,scrollView仍然只是针对某一个方向滑动

pagingEnable

该属性设置为YES时,可以控制用户滑动一下只翻一页。

UI_notes

image

UIView常用属性及方法

常用属性

NSInteger tag;

CGRect frame;

CGRect bounds;

CGPoint center;

CGAffineTransform transform;

BOOL multipleTouchEnable;

BOOL exclusiveTouch;

UIView *superView;

NSArray *subViews;

UIWindow *window;

UIColor *backgroundColor;

CGFloat alpa;

BOOL opaque;

BOOL hidden;

常用方法

类方法

1
+ (id)initWithFrame:(CGRect)frame;

实例方法

1
2
3
4
5
6
- (void)removeFromSuperview;
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
- (void)addSubview:(UIView *)view;
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;

UIView常见子类

UIControl

常用属性

BOOL enable;

BOOL selected;

BOOL highlighted;

UIControlState state;<readonly>

BOOL touchInside;<readonly>

实例方法

1
2
3
4
- (void)addTarget:(id)target action:(SEL)action forControlEvent:(UIControlEvent)controlEvent;
- (void)removeTarget:(id)target action:(SEL)action forControlEvent:(UIControlEvent)controlEvent;
- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent)event;
- (void)sendActionsForControlEvents:(UIControlEvent)controlEvents;

UIControl常见子类

UIButton

常用属性

UIButtonType buttonType;<readonly>

NSString *currentTitle;<readonly>

UIColor *currentColor;<readonly>

UIImage *currentImage;<readonly>

UIImage *currentBackgroundImage;<readonly>

NSAttributedString *currentAttributedTitle;<readonly>

类方法

1
+ (id)buttonWithType:(UIButtonType)buttonType;

实例方法

1
2
3
4
5
6
7
8
9
10
- (void)setTitle:(NSString *)title forState:(UIControlState)state;
- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state;
- (void)setImage:(UIImage *)image forState:(UIControlState)state;
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;
- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state;
- (NSString *)titleForState:(UIControlState)state;
- (UIColor *)titleColorForState:(UIControlState)state;
- (UIImage *)imageForState:(UIControlState)state;
- (UIImage *)backgroundImageForState:(UIControlState)state;
- (NSAttributedString *)attributedStringForState:(UIControlState)state;

UISlider

常见属性

float value;

float minimumValue;

float maximumValue;

UIImage *minimumValue;

UIImage *maximumValue;

BOOL continuous;

UIColor *minimumTrackTintColor;

UIColor *maximumTrackTintColor;

UIColor *thumbTintColor;

readonly

UIImage *currentThumbImage;

UIImage *currentMinimumTrackImage;

UIImage *currentMaximumTrackImage;

实例方法

1
2
3
4
5
6
- (void)setThumbImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMinimumTrackImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMaximumTrackImage:(UIImage *)image forState:(UIControlState)state;
- (UIImage *)thumbImage forState:(UIControlState)state;
- (UIImage *)minimumTrackImage forState:(UIControlState)state;
- (UIImage *)maximumTrackImage forState:(UIControlState)state;

UITextField

常用属性

NSString *text;

UIColor *textColor;

UIFont *font;

NSTextAlignment textAlignment;

UITextBorderStyle borderStyle;

NSString *placeholder;

BOOL clearOnBeginEditing;

BOOL adjustsFontSizeToFitWidth;

CGFloat minimumFontSize;

id delegate;

UIImage *background;

UIImage *disabledBackground;

BOOL editing;

UITextFieldViewMode clearButtonMode;

UIView *leftView;

UITextFieldViewMode leftViewMode;

UIView *rightView;

UITextFieldViewMode rightViewMode;

UIView *inputView;

UIView *inputAccessoryView;

实例方法

1
2
- (void)drawPlaceholderInRect:(CGRect)rect;
- (void)drawTextInRect:(CGRect)rect;

UISegmentedControl

常用属性

UISegmentedControlStyle segmentedControlStyle;

NSUInteger numberOfSegments; <readonly>

UIColor *tintColor;

NSInteger selectedSegmentIndex;

实例方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (id)initWithItems:(NSArray *)items;
- (void)insertSegmentWithTitle:(NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated;
- (void)insertSegmentWithImage:(UIImage *)image atIndex:(NSUInteger)segment animated:(BOOL)animated;
- (void)removeSegmentAtIndex:(NSUInteger)segment animated:(BOOL)animated;
- (void)removeAllSegments;
- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment;
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segment;
- (void)setImage:(UIImage *)image forSegmentAtIndex:(NSUInteger)segment;
- (UIImage *)imageForSegmentAtIndex:(NSUInteger)segment;
- (void)setWidth:(CGFloat)width forSegmentAtIndex:(NSUInteger)segment;
- (CGFloat)widthForSegmentAtIndex:(NSUInteger)segment;
- (void)setEnabled:(BOOL)enabled forSegmentAtIndex:(NSUInteger)segment;
- (BOOL)isEnabledForSegmentAtIndex:(NSUInteger)segment;
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;

UIPageControl

常用属性

NSInteger numberOfPages;

NSInteger currentPage;

BOOL hidesForSinglePage;

BOOL defersCurrentPageDisplay; //点击翻页无效

UIColor *pageIndicatorTintColor;

UIColor *currentPageIndicatorColor;

实例方法

1
2
- (void)updateCurrentPageDisplay;
- (CGSize)sizeForNumberOfPages:(NSInteger)pageCount;

UISwitch

常用属性

UIColor *onTintColor;

UIColor *tintColor;

UIColor *thumbColor;

UIImage *onImage;

UIImage *offImage;

BOOL on;

实例方法

1
2
- (void)initWithFrame:(CGRect)frame;
- (void)setOn:(BOOL)on animated:(BOOL)animated;

UIDatePicker

常用属性

UIDatePicker datePickerMode;

NSLocale *locale;

NSTimeZone *timeZone;

NSDate *date;

NSDate *minimumDate;

NSDate *MaximumDate;

NSTimerInterval *countDownDuration;

NSInteger minuteInterval;

实例方法

1
- (void)setDate:(NSDate *)date animated:(BOOL)animated;

UILabel

常用属性

NSString *text;

UIFont *font;

UIColor *color;

UIColor *shadowColor;

CGSize shadowOffset;

NSTextAlignment textAlignment;

NSLineBreakMode lineBreakMode;

NSAttributedString attributedText;

UIColor *highlightedTextColor;

BOOL highlighted;

BOOL userInteractionEnabled;

BOOL enabled;

NSInteger numberOfLines;

BOOL adjustsFontSizeToFitWidth;

BOOL minimumFontSize;

实例方法

1
2
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines;
- (void)drawTextInRect:(CGRect)rect;

UIAlertView

常见属性

id delegate;

NSString *title;

NSString *message;

NSInteger cancelButtonIndex;

readonly

NSInteger numberOfButtons;

NSInteger firstOtherButtonIndex;

BOOL visible;

UIAlertViewStyle alertViewStyle;

实例方法

1
2
3
4
- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... ;
- (void)show;
- (void)dismissWithClickEdButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;
- (UITextField *)textFieldAtIndex:(NSInteger)textFieldIndex;

UIActionSheet

常见属性

id delegate;

NSString *title;

UIActionSheetStyle actionSheetStyle;

NSInteger cancelButtonIndex;

NSInteger destructiveButtonIndex;

readonly

NSInteger numberOfButtons;

NSInteger firstOtherButtonIndex;

BOOL visible;

实例方法

1
2
3
4
5
6
7
8
9
- (id)initWithTitle:(NSString *)title delegate:(id<UIActionSheetDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... ;
- (NSInteger)addButtonWithTitle:(NSString *)title;
- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex;
- (void)showFromToolbar:(UIToolBar *)view;
- (void)showFromTabBar:(UITabBar *)view;
- (void)showFromBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animates;
- (void)showFromRect:(CGRect)rect inView:(UIView *)view animated:(BOOL)animated;
- (void)showInView:(UIView *)view;
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;

UIImageView

常用属性

UIImage *image;

UIImage *highlightedImage;

BOOL userInteractionEnable;

BOOL highlighted;

NSArray *animationImages;

NSArray *highlightedAnimationImages;

NSTimeInterval animationDuration;

NSInteger animationRepeatCount;

UIColor tintColor;

实例方法

1
2
3
4
5
- (id)initWithImage:(UIImage *)image;
- (id)initWithImage:(UIImage *)image highlightedImage:(UIImage *)highlightedImage;
- (void)startAnimating;
- (void)stopAnimating;
- (BOOL)isAnimating;

UINavigationBar

常用属性

UIBarStyle barStyle;

id delegate;

BOOL translucent;

NSArray *items;

UIColor *tintColor;

UIColor *barTintColor;

UIImage *shadowImage;

NSDictionary *titleTextAttributes;

UIImage *backIndicatorImage;

UIImage *backIndicatorTransitionMaskImage;

readonly

UINavigationItem *topItem;

UINavigationItem *backItem;

实例方法

1
2
3
4
5
6
7
8
9
- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated;
- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated;
- (void)setItems:(NSArray *)items animated:(BOOL)animated;
- (void)setBackgroundImage:(UIImage *)backgroundImage forBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForBarPosition:(UIBarPosition)barPosition barMetrics:(UIBarMetrics)barMetrics;
- (void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0);
- (UIImage *)backgroundImageForBarMetrics:(UIBarMetrics)barMetrics;
- (void)setTitleVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics;
- (CGFloat)titleVerticalPositionAdjustmentForBarMetrics:(UIBarMetrics)barMetrics;

UITabBar

常用属性

id delegate;

NSArray *items;

UIBarStyle barStyle

UITabBarItem *selectedItem;

UIColor *tintColor;

UIColor *barTintColor;

BOOL translucent;

UIColor *selectedImageTintColor;

UIImage *backgroundImage;

UIImage *selectionIndicatorImage;

UIImage *shadowImage;

UITabBarItemPositioning itemPositioning;

CGFloat itemWidth;

CGFloat itemSpacing;

实例方法

1
2
3
4
- (void)setItems:(NSArray *)items animated:(BOOL)animated;
- (void)beginCustomizingItems:(NSArray *)items;
- (BOOL)endCustomizingAnimated:(BOOL)animated;
- (BOOL)isCustomizing;

UIToolbar

常用属性

UIBarStyle barStyle;

NSArray *items;

BOOL translucent;

UIColor *tintColor;

UIColor *barTintColor;

id delegate;

实例方法

1
2
3
4
5
- (void)setItems:(NSArray *)items animated:(BOOL)animated;
- (void)setBackgroundImage:(UIImage *)backgroundImage forToolbarPosition:(UIBarPosition)topOrBottom barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForToolbarPosition:(UIBarPosition)topOrBottom barMetrics:(UIBarMetrics)barMetrics;
- (void)setShadowImage:(UIImage *)shadowImage forToolbarPosition:(UIBarPosition)topOrBottom;
- (UIImage *)shadowImageForToolbarPosition:(UIBarPosition)topOrBottom;

UISearchBar

常用属性

UIBarStyle barStyle;

id delegate;

NSString *text;

NSString *prompt;

NSString *placeholder;

BOOL showsBookmarkButton;

BOOL showsCancelButton;

BOOL showsSearchResultsButton;

UIColor *tintColor;

UIColor *barTintColor;

UISearchBarStyle searchBarStyle;

UITextAutocapitalizationType autocapitalizationType;

UITextAutocorrectionType autocorrectionType;

UITextSpellCheckingType spellCheckingType;

UIKeyboardType keyboardType;

NSArray *scopeButtonTitles;

NSInteger selectedScopeButtonIndex;

BOOL showsScopeBar;

UIView *inputAccessoryView;

UIWebView

常用属性

id delegate;

readonly

BOOL canGoBack;

BOOL canGoForward;

BOOL loading;

UIScrollView *scrollView;

NSURLRequest *request;

实例方法

1
2
3
4
5
6
7
8
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
- (void)reload;
- (void)stopLoading;
- (void)goBack;
- (void)goForward;
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

UIPickerView

常用属性

id dataSource;

id delegate;

BOOL showsSelectionIndicator;

NSInteger numberOfComponents;<readonly>

实例方法

1
2
3
4
5
6
7
- (NSInteger)numberOfRowsInComponent:(NSInteger)component;
- (CGSize)rowSizeForComponent:(NSInteger)component;
- (UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component;
- (void)reloadAllComponents;
- (void)reloadComponent:(NSInteger)component;
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated;
- (NSInteger)selectedRowInComponent:(NSInteger)component;

UITableViewCell

常用属性

UITableViewStyle style; <readonly>

id dataSource;

id delegate;

CGFloat rowHeight;

CGFloat sectionHeaderHeight;

CGFloat sectionFooterHeight;

CGFloat estimatedRowHeight;

CGFloat estimatedSectionHeaderHeight;

CGFloat estimatedSectionFooterHeight;

UIEdgeInsets separatorInset;

UIView *backgroundView;

BOOL editing;

BOOL allowsSelection;

BOOL allowsSelectionDuringEditing;

BOOL allowsMultipleSelection;

BOOL allowsMultipleSelectionDuringEditing;

UIView *tableHeaderView;

UIView *tableFooterView;

NSInteger sectionIndexMinimumDisplayRowCount;

UIColor *sectionIndexColor;

UIColor *sectionIndexBackgroundColor;

UIColor *sectionIndexTrackingBackgroundColor;

UITableViewCellSeparatorStyle separatorStyle;

UIColor *separatorColor;

实例方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style;
- (void)reloadData;
- (void)reloadSectionIndexTitles;
- (NSInteger)numberOfSections;
- (NSInteger)numberOfRowsInSection:(NSInteger)section;
- (CGRect)rectForSection:(NSInteger)section;
- (CGRect)rectForHeaderInSection:(NSInteger)section;
- (CGRect)rectForFooterInSection:(NSInteger)section;
- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point;
- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell;
- (NSArray *)indexPathsForRowsInRect:(CGRect)rect;
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSArray *)visibleCells;
- (NSArray *)indexPathsForVisibleRows;
- (UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section;
- (UITableViewHeaderFooterView *)footerViewForSection:(NSInteger)section;
- (void)beginUpdates;
- (void)endUpdates;
- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection;
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)moveRowAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath;
- (NSIndexPath *)indexPathForSelectedRow;
- (NSArray *)indexPathsForSelectedRows;
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;
- (id)dequeueReusableHeaderFooterViewWithIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier;
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forHeaderFooterViewReuseIdentifier:(NSString *)identifier;
- (void)registerClass:(Class)aClass forHeaderFooterViewReuseIdentifier:(NSString *)identifier;

UIViewController

常用属性

UIView *view;

NSString *title;

readonly

NSString *nibName;

NSBundle *nibBundle;

UIStoryboard *storyboard;

UIViewController *parentViewController;

UIViewController *presentedViewController;

UIViewController *presentingViewController

实例方法

1
- (void)loadView;

UIViewController的常见子类

UITabBarController

常用属性

NSArray *viewControllers;

UIViewController *selectedViewController;

NSUInteger selectedIndex;

id delegate;

readonly

UITabBar *tabBar;

UINavigationController *moreNavigationController;

实例方法

1
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated;

UINavigationController

常用属性

id delegate;

NSArray *viewControllers;

BOOL toolbarHidden;

readonly

UIViewController *topViewController;

UIViewController *visibleViewController;

UINavigationBar *navigationBar;

UIToolbar toolbar;

实例方法

1
2
3
4
5
6
7
8
- (id)initWithRootViewController:(UIViewController *)rootViewController;
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (UIViewController *)popViewControllerAnimated:(BOOL)animated;
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated;
- (void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated;
- (void)setNavigationBarHidden:(BOOL)hidden animated:(BOOL)animated;
- (void)setToolbarHidden:(BOOL)hidden animated:(BOOL)animated;

UITableViewController

常用属性

UITableView *tableView;

BOOL clearsSelectionOnViewWillAppear;

UIRefreshControl *refreshControl;

实例方法

1
- (id)initWithStyle:(UITableViewStyle)style;

UIBarItem

常用属性

BOOL enable;

NSString *title;

UIImage *image;

UIImage *landscapeImagePhone;

UIEdgeInsets imageInsets;

UIEdgeInsets landscapeImagePhoneInsets;

NSInteger tag;

实例方法

1
2
- (void)setTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)state;
- (NSDictionary *)titleTextAttributesForState:(UIControlState)state;

UIBarButtonItem

常用属性

UIBarButtonItem style;

CGFloat width;

NSSet *possibleTitles;

UIView *customView;

SEL action;

id target;

实例方法

1
2
3
4
5
6
7
- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action;
- (id)initWithImage:(UIImage *)image landscapeImagePhone:(UIImage *)landscapeImagePhone style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action;
- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action;
- (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action;
- (id)initWithCustomView:(UIView *)customView;
- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics;
- (UIImage *)backgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics

UITabBarItem

常用属性

UIImage selectedImage;

NSString badgeValue;

实例方法

1
2
3
- (id)initWithTitle:(NSString *)title image:(UIImage *)image tag:(NSInteger)tag;
- (instancetype)initWithTitle:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage NS_AVAILABLE_IOS(7_0);
- (id)initWithTabBarSystemItem:(UITabBarSystemItem)systemItem tag:(NSInteger)tag;

UINavigationItem

常用属性

NSSting *title;

UIBarButtonItem *backBarButtonItem;

UIView *titleView;

NSString *prompt;

BOOL hidesBackButton;

NSArray *leftBarButtonItems;

NSArray *rightBarButtonItems;

BOOL leftItemsSupplementBackButton;

UIBarButtonItem *leftBarButtonItem;

UIBarButtonItem *rightBarButtonItem;

实例方法

1
2
3
4
5
6
- (id)initWithTitle:(NSString *)title;
- (void)setHidesBackButton:(BOOL)hidesBackButton animated:(BOOL)animated;
- (void)setLeftBarButtonItems:(NSArray *)items animated:(BOOL)animated;
- (void)setRightBarButtonItems:(NSArray *)items animated:(BOOL)animated;
- (void)setLeftBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated;
- (void)setRightBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated;