目录
1. UIImageView 图片
SDWebImage
从相册或相机获取图片
2. UILabel 文字
3. UITextField 文本输入框
4. UIButton 按钮
5. UITextView 多行文本
6. UIWebView 显示网页
7. UIScrollView 滚动视图
8. UICollectionView
9. UITableView
1. UIImageView 图片
// 创建(: UIView )
UIImageView *imgV=[UIImageView new];
[self.view addSubview:imgV];
[imgV autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
// 设置 图片
[imgV setImage:[UIImage imageNamed:@""]];
// 设置 图片模式
[imgV setContentMode:UIViewContentModeScaleAspectFill];
/*
缩放
UIViewContentModeScaleToFill, 默认
UIViewContentModeScaleAspectFit, 不会裁剪(会有黑边)
UIViewContentModeScaleAspectFill, 会裁剪
不缩放
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
*/
继承UIView所拥有:
// 设置 可交互(默认:不可交互)
[imgV setUserInteractionEnabled:true];
// 设置 是否剪裁
[imgV setClipsToBounds:true];
// 设置 边框色、边框宽度、是否剪裁
[imgV.layer setBorderColor:[UIColor redColor].CGColor];
[imgV.layer setBorderWidth:1.0];
[imgV.layer setMasksToBounds:true];
// 圆角
[imgV.layer setCornerRadius:30]; // 宽高一半则为圆
[imgV.layer setMasksToBounds:true];
帧动画
// 设置 数据源
NSArray *imgArr=@[[UIImage imageNamed:@""]];
[imgV setAnimationImages:imgArr];
// 设置 持续时间
[imgV setAnimationDuration:1.25];
// 设置 重复次数
[imgV setAnimationRepeatCount:CGFLOAT_MAX];
// 开始动画
[imgV startAnimating];
// 停止动画
[imgV stopAnimating];
// 获取 是否正在动画
BOOL isAni=imgV.isAnimating;
UIImage
动态加载
只用填写图片名,会动态选择@2x或@3x进行加载图片
获取本地图片
// 方式1:立刻解压并放入缓存直至app退出才清空
UIImage *img=[UIImage imageNamed:@""];
// 方式2:不会立刻解压
UIImage *img2=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"1.jpg" ofType:nil]];
获取网络图片
// 显示时解压,img被释放时释放缓存
// 方式1:通过NSdata创建时,UIImage 底层是调用 ImageIO 的 CGImageSourceCreateWithData() 方法。该方法有个参数叫 ShouldCache,在 64 位的设备上,这个参数是默认开启的。这个图片也是同样在第一次显示到屏幕时才会被解码,随后解码数据被缓存到 CGImage 内部。与 imageNamed 创建的图片不同,如果这个图片被释放掉,其内部的解码数据也会被立刻释放。
UIImage *img3=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://.../1.jpg"]]];
// 方式2:
// SDWebImage
SDWebImage
异步图像下载
支持GIF动画
保证相同的url不会下载多次
保证主线程永远不会被阻塞
使用:
pod 'SDWebImage'
#import "UIImageView+WebCache.h"
//
[imgV sd_setImageWithURL:[NSURL URLWithString:@""]];
[imgV sd_setImageWithURL:[NSURL URLWithString:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
[imgV sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""] options:SDWebImageLowPriority];
[imgV sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
[imgV sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""] options:SDWebImageLowPriority completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
[imgV sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@""] options:SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
} completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
/*
SDWebImageRetryFailed(失败后重试)
SDWebImageLowPriority(交互时就下载,影响流畅)
SDWebImageCacheMemoryOnly(只进行内存缓存)
SDWebImageProgressiveDownload(渐进式下载)
SDWebImageRefreshCached(刷新缓存,若地址改变图片不变则使用)
SDWebImageContinueInBackground(后台下载)
SDWebImageHandleCookies
SDWebImageAllowInvalidSSLCertificates(允许使用无效SSL)
SDWebImageHighPriority(优先下载)
SDWebImageDelayPlaceholder
SDWebImageTransformAnimatedImage
*/
// 动画
[imgV sd_setAnimationImagesWithURLs:@[[NSURL URLWithString:@""]]];
// 取消当前动画
[imgV sd_cancelCurrentAnimationImagesLoad];
获取照片
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <AVFoundation/AVCaptureDevice.h>
<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
// [self getPhoto];
-(void)getPhoto{
UIAlertController *alertAC=[UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
[alertAC addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
[self getPhoto:0];
}]];
[alertAC addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self getPhoto:1];
}]];
[alertAC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alertAC animated:true completion:^{
}];
}
-(void)getPhoto:(int)index{
// 创建UIImagePickerController
UIImagePickerController *imgPickC=[UIImagePickerController new];
imgPickC.delegate=self;
imgPickC.allowsEditing=true; // 允许获取图片时编辑图片
switch (index) {
case 0:{
//
if(![self isCanUsePhotos]){
[self showAlertView];
}else{
//
imgPickC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imgPickC animated:true completion:^{
}];
}
}
break;
case 1:{
//
if(![self isCanUseCamera]){
[self showAlertView];
}else{
imgPickC.sourceType=UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imgPickC animated:true completion:^{
}];
}
}
break;
default:
break;
}
}
// 是否 有使用相册权限
- (BOOL)isCanUsePhotos{
// if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
ALAuthorizationStatus authStatus =[ALAssetsLibrary authorizationStatus];
if (authStatus == ALAuthorizationStatusRestricted || authStatus == ALAuthorizationStatusDenied) {
// 无权限
return false;
}
}else {
PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
if (authStatus == PHAuthorizationStatusRestricted || authStatus == PHAuthorizationStatusDenied) {
// 无权限
return false;
}
}
return YES;
}
// 是否 有使用相机权限
-(BOOL)isCanUseCamera{
// if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
AVAuthorizationStatus authStatus=[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if(authStatus == AVAuthorizationStatusRestricted || authStatus==AVAuthorizationStatusDenied){
return false;
}
return true;
}
-(void)showAlertView{
// 无权限
UIAlertController *alertC=[UIAlertController alertControllerWithTitle:@"温馨提示" message:@"无法获取相机权限,去设置中心打开权限" preferredStyle:UIAlertControllerStyleAlert];
[alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}]];
[alertC addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"App-Prefs:root=Photos"]]];
}]];
[self presentViewController:alertC animated:true completion:^{
}];
return;
}
// dele
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//
[picker dismissViewControllerAnimated:YES completion:nil];// 销毁控制器
UIImage *image = info[UIImagePickerControllerOriginalImage];// 获得图片
NSData *imageDta=[UIImage representationImage:image];
}
图片格式
GIF 诞生于 1987 年
它有很多缺点,比如通常情况下只支持 256 种颜色、透明通道只有 1 bit、文件压缩比不高。它唯一的优势就是支持多帧动画
JPEG 诞生于 1992 年(是目前最常见的图片格式)
它只支持有损压缩,其压缩算法可以精确控制压缩比,以图像质量换得存储空间。
PNG 诞生在 1995 年
它本身的设计目的是替代 GIF 格式,所以它与 GIF 有更多相似的地方。
PNG 只支持无损压缩,所以它的压缩比是有上限的。相对于 JPEG 和 GIF 来说,它最大的优势在于支持完整的透明通道。
APNG 是 Mozilla 在 2008 年发布的一种图片格式,旨在替换掉画质低劣的 GIF 动画。
WebP 是 Google 在 2010 年发布的图片格式,希望以更高的压缩比替代 JPEG。它用 VP8 视频帧内编码作为其算法基础,取得了不错的压缩效果。它支持有损和无损压缩、支持完整的透明通道、也支持多帧动画,并且没有版权问题,是一种非常理想的图片格式。
BPG 是著名程序员 Fabrice Bellard 在去年 (2014年) 发布的一款超高压缩比的图片格式。BPG 使用 HEVC (即 H.265) 帧内编码作为其算法基础,当下最为先进的图片压缩格式.
Android 的图片编码解码是由 Skia 图形库负责的,Skia 通过挂接第三方开源库实现了常见的图片格式的编解码支持。目前来说,Android 原生支持的格式只有 JPEG、PNG、GIF、BMP 和 WebP (Android 4.0 加入),在上层能直接调用的编码方式也只有 JPEG、PNG、WebP 这三种。目前来说 Android 还不支持直接的动图编解码。
iOS 底层是用 ImageIO.framework 实现的图片编解码。目前 iOS 原生支持的格式有:JPEG、JPEG2000、PNG、GIF、BMP、ICO、TIFF、PICT,自 iOS 8.0 起,ImageIO 又加入了 APNG、SVG、RAW 格式的支持。在上层,开发者可以直接调用 ImageIO 对上面这些图片格式进行编码和解码。对于动图来说,开发者可以解码动画 GIF 和 APNG、可以编码动画 GIF。
2. UILabel 文字
// 创建label( : UIView)
UILabel *textLabel=[UILabel new];
[self.view addSubview:textLabel];
[textLabel autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
常用
// 设置 文本
[textLabel setText:@""];
// 设置 复杂文本
[textLabel setAttributedText:[NSAttributedString new]];
// 设置 字体
[textLabel setFont:[UIFont systemFontOfSize:16]];
// 设置 颜色
[textLabel setTextColor:[UIColor colorWithWhite:0.35 alpha:1]];
// 设置 对齐方式(左 右 居中)
[textLabel setTextAlignment:NSTextAlignmentLeft];
/*
NSTextAlignmentLeft
NSTextAlignmentRight
NSTextAlignmentCenter
*/
// 设置 行数(默认:1 ,0:则无限行)
[textLabel setNumberOfLines:0];
// 设置 省略mode(文本超范围时)
[textLabel setLineBreakMode:NSLineBreakByClipping];
/*
ByWordWrapping // 以单词为显示单位显示(后面部分不显示)(默认)
ByCharWrapping // 以字符为显示单位显示(后面部分不显示)
ByClipping // 剪切与控件宽度相同的内容长度(后半部分被删除)
ByTruncatingHead // 前面以…省略,尾部正常显示
ByTruncatingTail // 尾部以…省略,头部正常显示(常用)
ByTruncatingMiddle // 中间以…省略,头尾正常显示
*/
其他
// 设置 阴影颜色/位置
[textLabel setShadowColor:[UIColor blueColor]];
[textLabel setShadowOffset:CGSizeMake(0, -1)];
// 设置 是否高亮 , 高亮颜色
[textLabel setHighlighted:true];
[textLabel setHighlightedTextColor:[UIColor blackColor]];
// 设置 是否禁用控件 , 是否允许交互
[textLabel setEnabled:true];
[textLabel setUserInteractionEnabled:true];
// 设置 是否自适应字体(随控件宽和文本长度)(默认:false)
[textLabel setAdjustsFontSizeToFitWidth:true];
// ?
[textLabel setPreferredMaxLayoutWidth:10];
// ? 默认:false
[textLabel setAllowsDefaultTighteningForTruncation:true];
// ?
[textLabel setBaselineAdjustment:UIBaselineAdjustmentNone];
// textRect
CGRect textRect=[textLabel textRectForBounds:CGRectZero limitedToNumberOfLines:0];
// 设置 最小缩放系数
[textLabel setMinimumScaleFactor:10];
其他功能
// 去除str两端的空格
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
// 对URL百分号编码(标点符号/中文->百分号)
[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]
// 移除百分号编码
[str stringByRemovingPercentEncoding]
// data->str
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *str=[[NSString alloc] initWithData:data encoding:enc];
UIFont
Swift
UIFont.systemFontOfSize(18)
UIFont.boldSystemFontOfSize(18) // 粗体
UIFont.italicSystemFontOfSize(18) // 斜体
let arr=UIFont.familyNames() // 获取 系统提供的所有字体名
UIFont.fontNamesForFamilyName(字体) // 获取字体名
let font=UIFont.init(name: "Thonburi", size: 17) // 创建字体对象(可写从上方获取到的名字、或公司买的字体)
OC
UIFont *font=[UIFont systemFontOfSize:17];
UIFont *font2=[UIFont boldSystemFontOfSize:17];
UIFont *font3=[UIFont italicSystemFontOfSize:17];
// 获取系统自带字体
NSArray *fontFamilyArr=[UIFont familyNames];
for (NSString *fontName in fontFamilyArr) {
NSLog(@"%@",fontName);
}
// 使用系统自带字体
#define YTFONT(x,fontName) [UIFont fontWithName:fontName size:(x)]

NSMutableAttributedString 复杂文本
// 创建(文本Font,文本Color)
NSMutableAttributedString *muStr=[[NSMutableAttributedString alloc]initWithString:@"" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11],NSForegroundColorAttributeName:[UIColor blueColor]}];
// 追加单个属性(背景色)
[muStr addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 10)];
// 追加多个属性(下划线)
[muStr addAttributes:@{NSUnderlineStyleAttributeName:@(2),NSUnderlineColorAttributeName:[UIColor blueColor]} range:NSMakeRange(0, 10)];
// 字符间距(正数则 加宽),基线偏移(正数则 上偏),字符是否连体(0没有连体字符,1默认的连体字符)
[muStr setAttributes:@{NSKernAttributeName:@(10),NSBaselineOffsetAttributeName:@(10),NSLigatureAttributeName:@(2)} range:NSMakeRange(0, 10)];
文本字体(默认值:字体:Helvetica(Neue) ,字号:12)
NSFontAttributeName
文本颜色(默认值:黑色)
NSForegroundColorAttributeName
背景色(默认值为nil, 透明色)
NSBackgroundColorAttributeName
下划线(取值为 NSNumber)
NSUnderlineStyleAttributeName
下划线颜色(默认:黑色)
NSUnderlineColorAttributeName
删除线(取值为 NSNumber)
NSStrikethroughStyleAttributeName
/*
NSUnderlineStyleNone 不设置删除线
NSUnderlineStyleSingle 设置删除线为细单实线
NSUnderlineStyleThick 设置删除线为粗单实线
NSUnderlineStyleDouble 设置删除线为细双实线
*/
删除线颜色(默认:黑色)
NSStrikethroughColorAttributeName
是否连体(取值为NSNumber,0 表示字符不连体,1 表示使用默认的连体字符)
NSLigatureAttributeName
字符间距(取值为 NSNumber,正值加宽)
NSKernAttributeName
填充部分颜色(取值为 UIColor)
NSStrokeColorAttributeName
画笔宽度(取值为 NSNumber)
NSStrokeWidthAttributeName
阴影(取值为 NSShadow)
NSShadowAttributeName
/*
NSShadow *shadow1 = [[NSShadow alloc] init]; //NSShadow 对象比较简单,只有3个属性:阴影颜色,模糊半径和偏移
shadow1.shadowOffset = CGSizeMake(3, 3); //阴影偏移(X方向偏移和Y方向偏移)
shadow1.shadowBlurRadius = 0.5; //模糊半径
shadow1.shadowColor = [UIColor orangeColor]; //阴影颜色
*/
段落排版(取值为 NSParagraphStyle)
NSParagraphStyleAttributeName
「
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = self.lineSapce; // 字体的行间距
paragraphStyle.alignment = NSTextAlignmentJustified; // 文本对齐方式 左右对齐(两边对齐)
属性
alignment 对齐方式,取值枚举常量 NSTextAlignment
firstLineHeadIndent 首行缩进,取值 float
headIndent 除了首行之外的缩进,取值 float
tailIndent 行尾缩进,取值 float,段落宽
ineHeightMultiple 可变行高,乘因数,取值 float,改变的是行间距
maximumLineHeight 最大行高,取值 float,若其值小于默认行高,则行间距变小,若其值大于默认行高,则不会引起任何变化
minimumLineHeight 最小行高,取值 float,若其值大于默认行高,则行间距变大,若其值小于默认行高,则不会引起任何变化
lineSpacing 行距,取值 float
paragraphSpacing 段距,取值 float
paragraphSpacingBefore 段首空间,取值 float,最小取值为0
baseWritingDirection 句子方向,取值枚举常量 NSWritingDirection
/*
NSWritingDirectionLeftToRight 0
NSWritingDirectionNatural -1
NSWritingDirectionRightToLeft 1
*/
lineBreakMode 断行方式,取值枚举常量 NSLineBreakMode
/*
NSLineBreakByWordWrapping = 0, // 自动换行,单词切断
NSLineBreakByCharWrapping, // 自动换行,字母切断
NSLineBreakByClipping, // 非自动换行,不切断
NSLineBreakByTruncatingHead, // 非自动换行,行首切断
NSLineBreakByTruncatingTail, // 非自动换行,行尾切断
NSLineBreakByTruncatingMiddle // 非自动换行,中间切断
*/
hyphenationFactor 连字符属性,取值 0 - 1
」
文本附件(取值为NSTextAttachment对象,常用于文字图片混排)
NSAttachmentAttributeName
链接(取值为NSURL,点击后调用浏览器打开指定URL地址)
NSLinkAttributeName
文字排版方向(取值为 NSNumber,0 表示横排文本,1 表示竖排文本)
NSVerticalGlyphFormAttributeName
文字书写方向(从左向右书写或者从右向左书写)
NSWritingDirectionAttributeName
文本横向拉伸(正值拉伸)
NSExpansionAttributeName
字体倾斜度(取值为 NSNumber,正值右倾)
NSObliquenessAttributeName
基线偏移值(取值为 NSNumber,正值上偏)
NSBaselineOffsetAttributeName
文本特殊效果(取值为 NSString,只印刷有用)
NSTextEffectAttributeName
遍历富文本
NSMutableAttributedString *muStr=[[NSMutableAttributedString alloc]initWithString:@"" attributes:@{}];
[muStr enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, muStr.length) options:0 usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if ([value isKindOfClass:[NSTextAttachment class]]) {
NSTextAttachment * attachment = value;
CGFloat height = attachment.bounds.size.height;
attachment.bounds = CGRectMake(0, 0, 300, height);
}
}];
超文本转富文本
- (NSAttributedString *)stringFromHtmlStr:(NSString *)htmlStr{
NSData * htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * importParams = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
NSError * error = nil;
NSAttributedString * attributeString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];
return attributeString;
}
富文本转超文本
- (NSString *)htmStrFromAttributeStr:(NSAttributedString *)attributeStr{
NSDictionary * exportParams = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
NSData * htmlData = [attributeStr dataFromRange:NSMakeRange:(0, attributeStr.length) documentAttributes:exportParams error:nil];
htmlString = [[NSString alloc] initwithData:htmlData encoding:NSUTF8StringEncoding];
return htmlString;
}
修改附件的宽高(防止图片超出)
-(void)method{
NSMutableAttributedString *muStr=[[NSMutableAttributedString alloc]initWithString:@"" attributes:@{}];
[muStr enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, muStr.length) options:0 usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if ([value isKindOfClass:[NSTextAttachment class]]) {
NSTextAttachment * attachment = value;
CGFloat height = attachment.bounds.size.height;
attachment.bounds = CGRectMake(0, 0, 300, height);
}
}];
}
3. UITextField 文本输入框
[self.view addSubview:contentTF];
[contentTF autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
//-------------- 常用 --------------
// 设置 文本
[contentTF setText:@""];
// 设置 颜色
[contentTF setTextColor:[UIColor redColor]];
// 设置 对齐方式
[contentTF setTextAlignment:NSTextAlignmentLeft];
/*
NSTextAlignmentLeft
NSTextAlignmentCenter
NSTextAlignmentRight
*/
// 设置 字体
[contentTF setFont:[UIFont systemFontOfSize:17]];
// 设置 提示文本
[contentTF setPlaceholder:@""];
// 设置 提示文本颜色
[contentTF setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
// 设置 提示文本字体
[contentTF setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
// 设置 是否加密显示
[contentTF setSecureTextEntry:true];
// 获得焦点(成为第一响应者)
[contentTF becomeFirstResponder];
// 失去焦点(注销第一响应者)
//(只能隐藏自己的键盘,不能隐藏其他textF的键盘)
[contentTF resignFirstResponder];
// 结束所有编辑状态(隐藏所有键盘)
[self.view endEditing:true];
//-------------- 右侧x视图 --------------
// 设置 右侧x视图Mode
[contentTF setClearButtonMode:UITextFieldViewModeAlways];
/*
UITextFieldViewModeNever, 从不显示
UITextFieldViewModeWhileEditing, 仅编辑时
UITextFieldViewModeUnlessEditing, 除了编辑
UITextFieldViewModeAlways 一直显示
*/
// 设置 是否插入文本时清空数据
[contentTF setClearsOnInsertion:true];
//-------------- 两侧视图 --------------
// 设置 左侧视图mode
[contentTF setLeftViewMode:UITextFieldViewModeAlways];
/*
UITextFieldViewModeNever, 从不显示
UITextFieldViewModeWhileEditing, 仅编辑时
UITextFieldViewModeUnlessEditing, 除了编辑
UITextFieldViewModeAlways 一直显示
*/
// 设置 左侧视图
[contentTF setLeftView:[UIView new]];
// 设置 右侧视图mode、右侧视图
// 右视图会覆盖x清空按钮
[contentTF setRightViewMode:UITextFieldViewModeAlways];
[contentTF setRightView:[UIView new]];
//-------------- 键盘 --------------
// 设置 键盘Mode
[contentTF setKeyboardType:UIKeyboardTypeNumberPad];
/*
UIKeyboardTypeDefault 默认的 键盘
UIKeyboardTypeASCIICapable 纯英文字母的 键盘
UIKeyboardTypeNumbersAndPunctuation 数字和标点的 键盘
UIKeyboardTypeURL 便于输入数字的 键盘 (.com)
UIKeyboardTypeNumberPad 便于输入数字的 键盘(纯数字)
UIKeyboardTypePhonePad 便于拨号呼叫的 键盘(手机号)
UIKeyboardTypeNamePhonePad 便于聊天拨号的 键盘
UIKeyboardTypeEmailAddress 便于输入Email的 键盘 (@)
UIKeyboardTypeDecimalPad 用于输入数字和【小数点】的 键盘
UIKeyboardTypeTwitter 便于在网页上书写的 键盘
UIKeyboardTypeWebSearch
UIKeyboardTypeASCIICapableNumberPad
UIKeyboardTypeAlphabet
*/
// 设置 自定义键盘View
[contentTF setInputView:[UIView new]];
// 设置 自定义键盘上方View
[contentTF setInputAccessoryView:[UIView new]];
// 设置键盘右上角return按钮标题
[contentTF setReturnKeyType:UIReturnKeyDone];
/*
UIReturnKeyDefault, 完成
UIReturnKeyGo, 完成并跳到另一页
UIReturnKeyGoogle, 搜索
UIReturnKeyJoin, 注册用户或添加数据
UIReturnKeyNext, 继续下一步
UIReturnKeyRoute, 发送
UIReturnKeySearch,
UIReturnKeySend,
UIReturnKeyYahoo,
UIReturnKeyDone,
UIReturnKeyEmergencyCall,
UIReturnKeyContinue
*/
// 设置 键盘外观
[contentTF setKeyboardAppearance:UIKeyboardAppearanceDark];
/*
UIKeyboardAppearanceDefault, 浅灰色(默认颜色)
UIKeyboardAppearanceDark 黑色
UIKeyboardAppearanceLight 亮色,与Default很相似
UIKeyboardAppearanceAlert
*/
//-------------- rect --------------
CGRect rect=[contentTF borderRectForBounds:contentTF.bounds];
CGRect rect2=[contentTF textRectForBounds:contentTF.bounds];
CGRect rect3=[contentTF placeholderRectForBounds:contentTF.bounds];
CGRect rect4=[contentTF editingRectForBounds:contentTF.bounds];
CGRect rect5=[contentTF clearButtonRectForBounds:contentTF.bounds];
CGRect rect6=[contentTF leftViewRectForBounds:contentTF.bounds];
CGRect rect7=[contentTF rightViewRectForBounds:contentTF.bounds];
//-------------- 其他 --------------
// 设置边框Mode
[contentTF setBorderStyle:UITextBorderStyleNone];
/*
UITextBorderStyleNone, 无边框
UITextBorderStyleLine, 直线
UITextBorderStyleBezel, 边线+阴影
UITextBorderStyleRoundedRect 圆角 (默认白色背景,此时背景图无效)
*/
// 设置 背景色、背景图片
[contentTF setBackgroundColor:[UIColor blueColor]];
[contentTF setBackground:[UIImage imageNamed:@""]]; // 边框样式需为none
[contentTF setDisabledBackground:[UIImage imageNamed:@""]];
// 设置 内容纵向对齐方式
[contentTF setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
/*
UIControlContentVerticalAlignmentCenter
UIControlContentVerticalAlignmentTop
UIControlContentVerticalAlignmentBottom
UIControlContentVerticalAlignmentFill
*/
// 设置 内容横向对齐方式
[contentTF setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
/*
UIControlContentHorizontalAlignmentCenter
UIControlContentHorizontalAlignmentLeft
UIControlContentHorizontalAlignmentRight
UIControlContentHorizontalAlignmentFill
UIControlContentHorizontalAlignmentLeading
UIControlContentHorizontalAlignmentTrailing
*/
// 设置 是否自动补全
[contentTF setAutocorrectionType:UITextAutocorrectionTypeNo];
/*
UITextAutocorrectionTypeDefault,
UITextAutocorrectionTypeNo, 不自动更正
UITextAutocorrectionTypeYes, 自动更正
*/
// 设置 文本随控件缩放
[contentTF setAdjustsFontSizeToFitWidth:true];
// 设置 最小缩放字体
[contentTF setMinimumFontSize:14];
dele
// <UITextFieldDelegate>
[contentTF setDelegate:self];
// 是否允许开始编辑
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{return true;}
// 开始编辑后调用
- (void)textFieldDidBeginEditing:(UITextField *)textField{}
// 是否允许结束编辑
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{return true;}
// 结束编辑后调用
- (void)textFieldDidEndEditing:(UITextField *)textField{}
// 是否允许改变
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// 拿到如果改变后的字符串,判断
NSString *str=[textField.text stringByReplacingCharactersInRange:range withString:string];
return true;
}
// 是否允许清除
- (BOOL)textFieldShouldClear:(UITextField *)textField{return true;}
// 是否允许return
- (BOOL)textFieldShouldReturn:(UITextField *)textField{return true;}
notification
// 由textField发出的通知:
UITextFieldTextDidBeginEditingNotification
UITextFieldTextDidEndEditingNotification
UITextFieldTextDidChangeNotification // 用于联想词汇
// 由键盘视图发出的通知:
UIKeyboardWillShowNotification 即将弹出时 发送
UIKeyboardDidShowNotification 完成弹出时 发送
UIKeyboardWillHideNotification 即将隐藏时 发送
UIKeyboardDidHideNotification 完成隐藏时 发送
UIKeyboardWillChangeFrameNotification 即将改变frame时 发送
UIKeyboardDidChangeFrameNotification 完成改变frame时 发送
IQKeyboardManager第三方(方便键盘管理)
pod 'IQKeyboardManager'
4 . UIButton 按钮
//
UIButton *button=[UIButton new];
[self.view addSubview:button];
[button autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];
//-------------- 常用 --------------
// 设置 标题
[button setTitle:@"" forState:UIControlStateNormal];
/*
UIControlStateNormal 普通状态
UIControlStateHighlighted 触摸状态(高亮)
UIControlStateDisabled 禁用状态
UIControlStateSelected 选中状态
UIControlStateFocused
UIControlStateApplication
UIControlStateReserved
*/
// 设置 标题颜色
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
// 设置 字体
[button.titleLabel setFont:[UIFont systemFontOfSize:16]];
// 设置 标题阴影色
[button setTitleShadowColor:[UIColor redColor] forState:UIControlStateNormal];
// 设置 图片
[button setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
// 设置 图片显示模式
[button.imageView setContentMode:UIViewContentModeScaleToFill];
// 设置 标题偏移
[button setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
// 设置 图片偏移
[button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
// 设置 内容偏移
[button setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
// 设置 背景图片
[button setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
// 设置 背景颜色
[button setBackgroundColor:[UIColor redColor]];
// 设置 是否选中(true则进入UIControlStateSelected状态)
[button setSelected:true];
// 设置 是否允许交互
[button setUserInteractionEnabled:true];
// 添加 点击事件
[button addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];
//-------------- 继承自UIView --------------
// 设置 alpha透明度
[button setAlpha:0.5];
// 设置 是否隐藏
[button setHidden:true];
// 设置 填充色
[button setTintColor:[UIColor blueColor]];
// 设置是否可用
[button setEnabled:true];
// 设置 边框颜色、边框宽度、边框圆角、是否裁剪
[button.layer setBorderColor:[UIColor redColor].CGColor];
[button.layer setBorderWidth:1.0];
[button.layer setCornerRadius:5.0];
[button.layer setMasksToBounds:true];
//-------------- 其他 --------------
// 设置 不可用时是否变暗
[button setAdjustsImageWhenDisabled:true];
// 设置 触摸时是否变暗
[button setAdjustsImageWhenHighlighted:true];
// 设置 触摸时是否高亮
[button setShowsTouchWhenHighlighted:true];
// 设置 内容纵向、水平对齐方式
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
[button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
// 获取 img、bgImg、titleColor、titleShadowColor、title、AttributedTitle
UIImage *img=button.currentImage;
UIImage *bgImg=button.currentBackgroundImage;
UIColor *titleColor=button.currentTitleColor;
UIColor *shadowTitleColor=button.currentTitleShadowColor;
NSString *title=button.currentTitle;
NSAttributedString *titleStr=button.currentAttributedTitle;
SDWebImage
#import <SDWebImage/UIButton+WebCache.h>
[button sd_setImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal];
[button sd_setImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""]];
[button sd_setImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""] options:SDWebImageLowPriority];
[button sd_setImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
[button sd_setImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
[button sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal];
[button sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""]];
[button sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""] options:SDWebImageLowPriority];
[button sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""] options:SDWebImageLowPriority completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
[button sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
[button sd_setBackgroundImageWithURL:[NSURL URLWithString:@""] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@""] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
系统自带类型
UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
/*
UIButtonTypeCustom = 0, 前面不带图标, 默认文字颜色为白色,无触摸时高亮
UIButtonTypeSystem 前面不带图标, 默认文字颜色为蓝色,有触摸时高亮
UIButtonTypeDetailDisclosure, 前面带“!”图标按钮 ,默认文字颜色为蓝色,有触摸时高亮
UIButtonTypeInfoLight, 为感叹号“!”圆形按钮
UIButtonTypeInfoDark, 为感叹号“!”圆形按钮
UIButtonTypeContactAdd, 前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时高
UIButtonTypePlain
UIButtonTypeRoundedRect
*/
5. UITextView 多行文本
//
UITextView *contentTV=[UITextView new];
[self.view addSubview:contentTV];
// 成为第一响应者
[contentTV becomeFirstResponder];
// 注销第一响应者
[contentTV resignFirstResponder];
// 设置 frame(基本不用)
[contentTV setFrame:CGRectZero];
// 设置 文本
[contentTV setText:@""];
// 设置 颜色
[contentTV setTextColor:[UIColor redColor]];
// 设置 字体
[contentTV setFont:[UIFont systemFontOfSize:15]];
// 设置 是否允许滚动
[contentTV setScrollEnabled:true];
// 设置 文本是否可选
[contentTV setSelectable:true];
// 设置 文本是否可编辑
[contentTV setEditable:true];
// 设置 允许选择的范围
[contentTV setSelectedRange:NSMakeRange(0, 10)];
// 设置 键盘View
[contentTV setInputView:[UIView new]];
// 设置 键盘头部View
[contentTV setInputAccessoryView:[UIView new]];
// 设置 复杂标题
[contentTV setAttributedText:[NSAttributedString new]];
// 滚动至指定范围
[contentTV scrollRangeToVisible:NSMakeRange(0, 10)];
// 设置 背景色
[contentTV setBackgroundColor:[UIColor blueColor]];
// 设置 边框色、边宽宽度
[contentTV.layer setBorderColor:[UIColor blueColor].CGColor];
[contentTV.layer setBorderWidth:1.0];
// 设置 圆角
[contentTV.layer setCornerRadius:5.0];
[contentTV.layer setMasksToBounds:true];
// 判断 输入法是否是中文
BOOL isChina=[[[contentTV textInputMode] primaryLanguage]isEqualToString: @"en-US"];
// 获取 选中文本的范围
UITextRange *selectedRange = [contentTV markedTextRange];
// 获取 高亮部分?
UITextPosition *position = [contentTV positionFromPosition:selectedRange.start offset:0];
dele
// dele
[contentTV setDelegate:self];
// 开始编辑前调用(是否允许开始编辑)
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{return true;}
// 开始编辑后调用
- (void)textViewDidBeginEditing:(UITextView *)textView{}
// 结束编辑前调用(是否允许结束编辑)
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{return true;}
// 结束编辑后调用
- (void)textViewDidEndEditing:(UITextView *)textView{}
// 编辑内容后调用(是否允许编辑)用于控制字符长度
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ return true;}
// 文本内容改变后调用
- (void)textViewDidChange:(UITextView *)textView{}
// 选中文本变化后调用
- (void)textViewDidChangeSelection:(UITextView *)textView{}
// ?
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{return true;};
// ?
- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{return true;};
6. UIWebView
UIWebView : UIView <NSCoding, UIScrollViewDelegate>
// 创建
UIWebView *webV=[UIWebView new];
[self.view addSubview:webV];
// 设置 是否显示纵向滚动条
[webV.scrollView setShowsVerticalScrollIndicator:true];
// 设置 是否显示横向滚动条
[webV.scrollView setShowsHorizontalScrollIndicator:true];
// 设置是否缩放到适合屏幕大小
[webV setScalesPageToFit:true];
// 设置 是否允许media后台播放
[webV setAllowsInlineMediaPlayback:true];
// 获取scrollView(只读)
UIScrollView *scrollView=webView.scrollView;
// 获取NSURLRequest (只读)
NSURLRequest *request=webView.request;
显示网页
// 方式一:加载 url
[webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
// 方式二:加载 htmlStr
[webV loadHTMLString:@"<p>hello</p>" baseURL:nil];
// 方式三:加载 nsdata
[webView loadData:[NSData data] MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];
例:加载本地文件
NSString *path=[[NSBundle mainBundle] pathForResource:@"1.docx" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:path];
[webView loadData:data MIMEType:@"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:@"UTF-8" baseURL:nil];
/*
1.docx
application/vnd.openxmlformats-officedocument.wordprocessingml.document
2.pdf
application/pdf
3.txt
text/plain
4.html
text/html
*/
// 获取 页面数量
NSInteger pageCount=webV.pageCount;
// 是否 可以回退
BOOL isCanBack=[webV canGoBack];
// 是否 可以前进
BOOL isCanForward=[webV canGoForward];
// 回退
[webV goBack];
// 前进
[webV goForward];
// 是否 正在加载
BOOL isLoading=[webV isLoading];
// 重新加载
[webV reload];
// 停止加载
[webV stopLoading];
// 翻页效果(当网页的大小超出view时,将网页以翻页的效果展示)
@property (nonatomic) UIWebPaginationMode paginationMode;
/*
UIWebPaginationModeUnpaginated, // 不使用翻页效果
UIWebPaginationModeLeftToRight, // 将网页超出部分分页,从左向右进行翻页
UIWebPaginationModeTopToBottom, // 将网页超出部分分页,从上向下进行翻页
UIWebPaginationModeBottomToTop, // 将网页超出部分分页,从下向上进行翻页
UIWebPaginationModeRightToLeft // 将网页超出部分分页,从右向左进行翻页
*/
// 分页模式
@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode;
/*
UIWebPaginationBreakingModePage,
UIWebPaginationBreakingModeColumn
*/
// 每一页的长度
@property (nonatomic) CGFloat pageLength;
// 每一页的间距
@property (nonatomic) CGFloat gapBetweenPages;
// 是否允许分屏播放
@property (nonatomic) BOOL allowsPictureInPictureMediaPlayback;
// 是否允许长按链接预览(支持3D Touch的设备),default is NO
@property (nonatomic) BOOL allowsLinkPreview;
// 是否使用内嵌HTML5播放视频还是用本地的全屏控制。
// 内嵌还必须的是在HTML中的video元素必须包含webkit-playsinline属性。
// iPhone Safari defaults to NO. iPad Safari defaults to YES
@property (nonatomic) BOOL allowsInlineMediaPlayback;
// 是否允许自动播放,默认为YES
@property (nonatomic) BOOL mediaPlaybackRequiresUserAction;
// 音频播放是否支持air play功能,默认为YES
@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay;
// 是否网页内容下载完毕才开始渲染web视图,默认为NO
@property (nonatomic) BOOL suppressesIncrementalRendering;
// 是否在弹出键盘后允许用户交互,默认YES
@property (nonatomic) BOOL keyboardDisplayRequiresUserAction;
// 获取web页面内容信息
NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];
/*
JavaScript的执行时间被限定在10秒钟,如果执行时间超过10秒,那么页面就停止执行这个脚本。
JavaScript的执行或许能够阻塞主线程,所以当脚本执行的时候不允许用户影响页面的加载。
JavaScript的内存分配被限制在10M,如果超出这个限制那么页面会发生异常。
*/
dele
// dele<UIWebViewDelegate>
[webV setDelegate:self];
// 是否应该加载(加载前调用)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
return true;
/*
UIWebViewNavigationTypeLinkClicked, 用户触击了一个链接
UIWebViewNavigationTypeFormSubmitted, 用户提交了一个表单
UIWebViewNavigationTypeBackForward, 用户触击前进或返回按钮
UIWebViewNavigationTypeReload, 用户触击重新加载的按钮
UIWebViewNavigationTypeFormResubmitted, 用户重复提交表单
UIWebViewNavigationTypeOther 发生其它行为
*/
}
// 开始加载后调用
- (void)webViewDidStartLoad:(UIWebView *)webView{}
// 加载完毕后调用
- (void)webViewDidFinishLoad:(UIWebView *)webView{}
// 加载失败后调用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{}
7. UIScrollView 滚动视图
UIScrollView *contentSV=[UIScrollView new];
[self.view addSubview:contentSV];
// 设置 frame(显示区域的大小)
[contentSV setFrame:CGRectZero];
// 设置 contentSize(内容的大小(默认为CGSizeZero,必须设置,否则不滚动)(宽为0时只滚动高))
[contentSV setContentSize:CGSizeMake(100, 100)];
// 设置 偏移量(让scrollView滚动x,y)(固定的UI左上角-移动的内容左上角)
[contentSV setContentOffset:CGPointMake(100, 100)];
[contentSV setContentOffset:CGPointZero animated:true];
// 设置 内容周边(上,左,下,右)
[contentSV setContentInset:UIEdgeInsetsZero];
// 设置 弹簧效果 滚动到边界时反弹(默认true)
[contentSV setBounces:true];
// 设置 是否以页为单位(默认false)滚动
[contentSV setPagingEnabled:true];
// 设置 最小缩放比例
[contentSV setMinimumZoomScale:0.5];
// 设置 最大缩放比例
[contentSV setMaximumZoomScale:2.0];
// 设置 是否允许滚动
[contentSV setScrollEnabled:true];
// 设置 是否只允许一个方向滚动(默认false)
[contentSV setDirectionalLockEnabled:true];
// 设置 是否纵向永远可滚动
// 当sv中的子View小于sv的可视大小时默认不允许滚动,设置后允许纵向滚动(默认false )
[contentSV setAlwaysBounceVertical:true];
// 设置 是否横向永远可滚动
[contentSV setAlwaysBounceHorizontal:true];
// 设置 滚动条距sv边距
[contentSV setScrollIndicatorInsets:UIEdgeInsetsZero];
// 设置 是否允许纵向滚动
[contentSV setShowsVerticalScrollIndicator:true];
// 设置 是否允许横向滚动
[contentSV setShowsHorizontalScrollIndicator:true];
// 设置 滚动条格式
[contentSV setIndicatorStyle:UIScrollViewIndicatorStyleBlack];
/*
UIScrollViewIndicatorStyleDefault,
UIScrollViewIndicatorStyleBlack,
UIScrollViewIndicatorStyleWhite
*/
// 获取 是否开始触摸
BOOL isTracking=[contentSV isTracking];
// 获取 是否开始触摸滑动
BOOL isDragging=[contentSV isDragging];
// 获取 是否手指释放后正在滑动
BOOL isDecelerating=[contentSV isDecelerating];
// 设置 是否允许滚动到顶部(可定义一个按钮用来滚动到最上方)
[contentSV setScrollsToTop:true];
// 滚动到rect,一般用contentOffset
[contentSV scrollRectToVisible:CGRectZero animated:true];
// 设置 手指抬起后的减速率
[contentSV setDecelerationRate:UIScrollViewDecelerationRateNormal];
/*
UIScrollViewDecelerationRateNormal
UIScrollViewDecelerationRateFast
*/
// 设置 滚动时键盘的显示style,默认不消失
[contentSV setKeyboardDismissMode:UIScrollViewKeyboardDismissModeOnDrag];
/*
UIScrollViewKeyboardDismissModeNone
UIScrollViewKeyboardDismissModeOnDrag
UIScrollViewKeyboardDismissModeInteractive
*/
//
// 获取 是否正在缩放
BOOL isZooming=[contentSV isZooming];
// 获取 是否缩放超出临界值
BOOL isZoomBouncing=[contentSV isZoomBouncing];
// 获取 缩当前放比例
CGFloat zoomScale=[contentSV zoomScale];
// 缩放到某矩形块
[contentSV zoomToRect:CGRectMake(0, 0, 100, 100) animated:true];
// 缩放(动画)
[contentSV setZoomScale:0.6 animated:true];
[contentSV setZoomScale:0.6];
// ?
[contentSV setCanCancelContentTouches:true];
// ?
[contentSV setDelaysContentTouches:true];
// 设置 背景色
[contentSV setBackgroundColor:[UIColor blackColor]];
// dele<UIScrollViewDelegate>
[contentSV setDelegate:self];
// 滑动时调用(持续触发)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{}
// 是否允许滚动到顶部
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView{return true;}
// 滚动到顶部后调用
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{}
// 1.手指即将触摸前调用(此时可销毁计时器)
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{}
// 2.手指离开后调用(此时可启动计时器) (decelerate:是否会继续滚动)
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{}
// 3.即将减速时调用
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{}
// 4.停止减速时调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{}
// 5.完全停止后调用(手动滑动不调用) 设置偏移量调用
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{}
//
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{}
//
- (void)scrollViewDidChangeAdjustedContentInset:(UIScrollView *)scrollView{};
// (缩放必须+maxmin缩放值,否则不能缩放)
// 返回要缩放的对象
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{}
// 缩放时调用(持续触发)
- (void)scrollViewDidZoom:(UIScrollView *)scrollView{}
// 开始缩放前调用
- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view{}
// 结束缩放后调用
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view atScale:(CGFloat)scale{}
8. UICollectionView
//
// 1.创建 布局对象
UICollectionViewFlowLayout *fl=[UICollectionViewFlowLayout new];
// 设置 纵行滚动
[fl setScrollDirection:UICollectionViewScrollDirectionVertical];
// 设置 最小行间距(也可通过dele方法设置)
[fl setMinimumLineSpacing:10];
// 设置 最小项间距(也可通过dele方法设置)
[fl setMinimumInteritemSpacing:10];
// 设置 项大小(也可通过dele方法设置)
[fl setItemSize:CGSizeMake(200, 100)];
// 设置 组内边距(也可通过dele方法设置)
[fl setSectionInset:UIEdgeInsetsZero];
// 垂直滚动时 高起作用(宽无效 为collV宽),水平滚动时 宽起作用(高无效 为collV高)
// 设置 头视图大小(也可通过dele方法设置)
[fl setHeaderReferenceSize:CGSizeMake(100, 100)];
// 设置 尾视图大小(也可通过dele方法设置)
[fl setFooterReferenceSize:CGSizeMake(100, 100)];
// 2.创建 UICollectionView : UIScrollView
UICollectionView *contentCollV=[[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];
// 设置 dele<UICollectionViewDelegate,UICollectionViewDataSource>
[contentCollV setDelegate:self];
[contentCollV setDataSource:self];
[self.view addSubview:contentCollV];
// 3.注册 cell
[contentCollV registerClass:[] forCellWithReuseIdentifier:NSStringFromClass([])];
[contentCollV registerNib:[UINib nibWithNibName:@"" bundle:nil] forCellWithReuseIdentifier:@""];
// 3.注册 head、foot视图
[contentCollV registerClass:[] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([])];
[contentCollV registerNib:[UINib nibWithNibName:@"" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@""];
// 删除 指定组
[contentCollV deleteSections:[NSIndexSet indexSetWithIndex:0]];
// 删除 指定项
[contentCollV deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]];
// 插入 指定组
[contentCollV insertSections:[NSIndexSet indexSetWithIndex:0]];
// 插入 指定项
[contentCollV insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]];
// 获取 指定indexPath对应的项
UICollectionViewCell *cell=(UICollectionViewCell *)[contentCollV cellForItemAtIndexPath:indexPath];
自定义CELL MyCell: UICollectionViewCell
-(instancetype)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
if(self){
[self setupUI];
}
return self;
}
自定义头尾视图 :UICollectionReusableView
// 初始化控件
-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes{
}
dele
<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
// 返回 组数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{return 0;}
// 返回 每组的项数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{return 0;}
// 返回 每项大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{return CGSizeMake(100, 100);}
// 返回 每项的上下左右边距(注意:仔细调整)
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{return UIEdgeInsetsZero;}
// 返回 每项
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"" forIndexPath:indexPath];
return cell;
}
// 返回 每项的最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{return CGFLOAT_MIN;}
// 返回 每项的最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{return CGFLOAT_MIN;}
// 返回 头视图的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{return CGSizeMake(100, 100);}
// 返回 尾视图的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{return CGSizeMake(100, 100);}
// 返回 头视图、尾视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
if([kind isEqualToString:UICollectionElementKindSectionHeader]){
UICollectionReusableView *headV=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"" forIndexPath:indexPath];
return headV;
}else{
UICollectionReusableView *footV=[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"" forIndexPath:indexPath];
return footV;
}
return [UICollectionReusableView new];
}
// 是否允许选择项
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 选择某项后调用
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{}
// 是否允许反选项
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 反选某项后调用
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{}
// 是否 允许项高亮
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 项高亮后调用
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{}
// 项反高亮后调用
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{}
// 是否允许移动项
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 移动项后调用
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath{}
// 返回 索引
- (NSArray<NSString *> *)indexTitlesForCollectionView:(UICollectionView *)collectionView{return @[@"A",@"B"];}
//
- (NSIndexPath *)collectionView:(UICollectionView *)collectionView indexPathForIndexTitle:(NSString *)title atIndex:(NSInteger)index{}
// 长按时是否显示菜单
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 是否允许某操作
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender{return true;}
// 进行某种操作时调用
- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender{}
// 即将显示项时调用
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{}
// 即将显示头尾视图时调用
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{}
// 结束显示项时调用
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{}
// 结束显示头尾视图时调用
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{}
//
- (nonnull UICollectionViewTransitionLayout *)collectionView:(UICollectionView *)collectionView transitionLayoutForOldLayout:(UICollectionViewLayout *)fromLayout newLayout:(UICollectionViewLayout *)toLayout{}
// Focus
- (BOOL)collectionView:(UICollectionView *)collectionView canFocusItemAtIndexPath:(NSIndexPath *)indexPath{}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldUpdateFocusInContext:(UICollectionViewFocusUpdateContext *)context{};
- (void)collectionView:(UICollectionView *)collectionView didUpdateFocusInContext:(UICollectionViewFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator{}
- (nullable NSIndexPath *)indexPathForPreferredFocusedViewInCollectionView:(UICollectionView *)collectionView{}
//
- (NSIndexPath *)collectionView:(UICollectionView *)collectionView targetIndexPathForMoveFromItemAtIndexPath:(NSIndexPath *)originalIndexPath toProposedIndexPath:(NSIndexPath *)proposedIndexPath{}
//
- (CGPoint)collectionView:(UICollectionView *)collectionView targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset{}
//
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSpringLoadItemAtIndexPath:(NSIndexPath *)indexPath withContext:(id<UISpringLoadedInteractionContext>)context{}
8.1 流布局
9. UITableView
// 创建
UITableView *contentTV=[UITableView new];
// dele<UITableViewDelegate,UITableViewDataSource>
[contentTV setDelegate:self];
[contentTV setDataSource:self];
// 设置 分割线style
[contentTV setSeparatorStyle:UITableViewCellSeparatorStyleNone];
// 设置 纵向滚动条是否隐藏
[contentTV setShowsVerticalScrollIndicator:false];
// 设置 背景色
[contentTV setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:contentTV];
// 注册cell
[contentTV registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
[contentTV registerNib:[UINib nibWithNibName:@"" bundle:nil] forCellReuseIdentifier:@""];
// 注册 head、foot视图
[contentTV registerClass:[] forHeaderFooterViewReuseIdentifier:@""];
[contentTV registerNib:[UINib nibWithNibName:@"" bundle:nil] forHeaderFooterViewReuseIdentifier:@""];
// 设置 头、尾视图
[contentTV setTableHeaderView:[UIView new]];
[contentTV setTableFooterView:[UIView new]];
// 设置 背景View
[contentTV setBackgroundView:[UIView new]];
// 设置 是否允许编辑
[contentTV setEditing:true];
[contentTV setEditing:true animated:true];
// 设置 行高(可通过dele方法实现)
[contentTV setRowHeight:65];
// 设置 组头、组尾视图高(可通过dele方法实现)
[contentTV setSectionHeaderHeight:10];
[contentTV setSectionFooterHeight:10];
// 设置 预估行高
[contentTV setEstimatedRowHeight:10];
// 刷新 UI(更新dataSourceArr数据后)
[contentTV reloadData];
// 刷新 指定组
[contentTV reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop];
/*
UITableViewRowAnimationFade,
UITableViewRowAnimationRight,
UITableViewRowAnimationLeft,
UITableViewRowAnimationTop,
UITableViewRowAnimationBottom,
UITableViewRowAnimationNone,
UITableViewRowAnimationMiddle,
UITableViewRowAnimationAutomatic
*/
// 刷新 指定行
[contentTV reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
// 刷新 索引标题
[contentTV reloadSectionIndexTitles];
// 滚动到 指定行
[contentTV scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:true];
// 滚动到 最近被选中的cell
[contentTV scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:true];
// 移动 行
[contentTV moveRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] toIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
// 移动 组
[contentTV moveSection:0 toSection:1];
// 删除 行
[contentTV deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
// 删除 组
[contentTV deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop];
// 插入 行
[contentTV insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
// 插入 组
[contentTV insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationTop];
// 选中某行
[contentTV selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:true scrollPosition:UITableViewScrollPositionTop];
// 反选某行
[contentTV deselectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:true];
// 获取 选中行indexPath
NSIndexPath *indexPath=[contentTV indexPathForSelectedRow];
// 获取 选中行indexPathArr
NSArray *indexPathArr=[contentTV indexPathsForSelectedRows];
// 获取 指定indexPath的cell
UITableViewCell *cell=[contentTV cellForRowAtIndexPath:indexPath];
// 选中 cell
[cell setSelected:true];
// 设置 编辑时允许多选
[contentTV setAllowsSelectionDuringEditing:true];
9.1 CELL
自定义CELL
:UITableViewCell
系统CELL
// 类型
UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"iden"];
/*
UITableViewCellStyleDefault, // 从左到右(imageView(可选)->textLabel
UITableViewCellStyleValue1, // 从左到右(imageView(可选)->textLabel(粗黑)->detailTextLabel(右侧、蓝)
UITableViewCellStyleValue2, // 从左到右(imageView(可选)->textLabel(蓝)->detailTextLabel(紧跟textLabel)
UITableViewCellStyleSubtitle // 从左到右(imageView(可选)->textLabel(上方、粗黑),detailTextLabel(下方、灰色)
*/
// 右侧小图标
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
/*
UITableViewCellAccessoryNone, // 无
UITableViewCellAccessoryDisclosureIndicator, // >
UITableViewCellAccessoryDetailDisclosureButton // ?>
UITableViewCellAccessoryCheckmark, // 对勾
UITableViewCellAccessoryDetailButton // 信息按钮
*/
// 右侧小图标(自定义)
[cell setAccessoryView:[UIView new]];
//
[cell setSeparatorInset:UIEdgeInsetsZero];
[cell setLayoutMargins:UIEdgeInsetsZero];
// 选中后的状态(tableView选中后,它的子控件的背景色将没了)
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
/*
UITableViewCellSelectionStyleNone,
UITableViewCellSelectionStyleBlue,
UITableViewCellSelectionStyleGray,
UITableViewCellSelectionStyleDefault
*/
9.2 dele
常用
// 返回 组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{return 0;}
// 返回 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{return 0;}
// 返回 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 65;
}
// 返回每行(每当重新出现在界面上时,都调用一次)(向cell中添加子控件时最好加在contentView中:统一管理)
// 内存中:可见队列和可重用队列,当cell滚动出视图后,则从可见队列移出移入到可重用队列;当cell显示在界面上时先从可重用队列中查找,若有则从可重用队列移出并移入可见队列,若没有则重新创建并放入可见队列
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"" forIndexPath:indexPath];
return cell;
}
点击
// 点击一行时调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{}
// 反选一行时调用
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{}
// 即将选中一行时调用
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{}
// 即将反选反选一行时调用
- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath{}
组
// 返回 组头视图高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{return 100;}
// 返回 组尾视图高
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{return 100;}
// 返回 组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{return [UIView new];}
// 返回 组尾视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{return [UIView new];}
// 返回 组头标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{return @"";}
// 返回 组尾标题
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{return @"";}
索引
// 返回 索引标题数组
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{return @[@"A"];}
// 返回 标题索引(每次点击索引标题后调用 跳到相应section,从0开始,加上搜索图标后-1)
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{return index;}
移动
// 返回 是否允许移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 移动后调用
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{}
// 移动行的过程中会多次调用(用来限制只能在本section中移动)
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath{return sourceIndexPath;}
左滑编辑
// 返回 向左滑动时,自定义按钮上的删除文本
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{return @"删";}
// 向左滑动时,自定义右边编辑按钮 (可编辑类型)
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
return @[[UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
}]];
}
// 返回 是否允许编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 返回 每行的编辑style
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleDelete;
/*
UITableViewCellEditingStyleNone,
UITableViewCellEditingStyleDelete,
UITableViewCellEditingStyleInsert
*/
}
// 即将编辑前调用
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{}
// 结束编辑后调用
- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(nullable NSIndexPath *)indexPath{}
// 编辑时调用
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{}
// 返回 编辑时是否对指定行向左缩进
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 返回 每行行缩进
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath{return 60;}
长按
// 返回 每行长按时 是否允许Menu菜单
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 返回 每行出现菜单时 可以做某种操作
- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender{return true;}
// 点击菜单 某项后调用
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender{}
cell右侧图标
// 返回 cell右侧图标
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellAccessoryCheckmark;
/*
UITableViewCellAccessoryNone,
UITableViewCellAccessoryDisclosureIndicator,
UITableViewCellAccessoryDetailDisclosureButton
UITableViewCellAccessoryCheckmark,
UITableViewCellAccessoryDetailButton
*/
}
// 点击 cell右侧图标时调用
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{}
高亮
// 是否 允许行高亮
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{return true;}
// 某行 高亮后调用
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath{}
// 某行 被反高亮后调用
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath{}
即将显示
// 即将显示cell时调用
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{}
// 即将显示head视图时调用
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{}
// 即将显示foot视图时调用
- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section{}
// 显示完毕cell后调用
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath{}
// 显示完毕head后调用
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section{}
// 显示完毕foot后调用
- (void)tableView:(UITableView *)tableView didEndDisplayingFooterView:(UIView *)view forSection:(NSInteger)section{}
预估高
// 返回预估行高、预估组头视图高、预估组尾视图高
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section{}
//
- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath{}
- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath{}
// Focus
- (BOOL)tableView:(UITableView *)tableView canFocusRowAtIndexPath:(NSIndexPath *)indexPath{}
- (BOOL)tableView:(UITableView *)tableView shouldUpdateFocusInContext:(UITableViewFocusUpdateContext *)context{}
- (void)tableView:(UITableView *)tableView didUpdateFocusInContext:(UITableViewFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator{}
- (nullable NSIndexPath *)indexPathForPreferredFocusedViewInTableView:(UITableView *)tableView{}
- (BOOL)tableView:(UITableView *)tableView shouldSpringLoadRowAtIndexPath:(NSIndexPath *)indexPath withContext:(id<UISpringLoadedInteractionContext>)context{}
9.3 添加上下拉刷新
9.4 NSIndexPath
网友评论