首页 文章 精选 留言 我的

精选列表

搜索[ios],共10000篇文章
优秀的个人博客,低调大师

【iOS 开发】SnapKit 是怎样炼成的

前言 这是对 Swift 布局框架 SnapKit 的源码的一点分析,尝试搞清,一个好的布局框架,背后都做了些什么。 介绍 SnapKit 中的一些类 ConstraintView 等同于 UIView ConstraintAttributes 用于构造约束关系的各种元素(上下左右等) ConstraintDescription 包含了包括 ConstraintAttributes 在内的各种与约束有关的元素,一个 ConstraintDescription 实例,就可以提供与一种约束有关的所有内容。 ConstraintMaker 构造约束关系的起点,提供了 <code>makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void)</code> 方法来为程序员提供了描述约束的空间,也可以通过 left right top bottom centerX centerY 等属性,去生成一个 ConstraintMakerExtendable 实例(见下面) ConstraintMakerExtendable(继承 ConstraintMakerRelatable) 提供 left right top bottom leading trailing edges size margins 等内容,用以产生一个 ConstraintMakerRelatable 类型的实例 ConstraintMakerRelatable 直接用于构造约束关系,也是常用方法 <code>equalTo(_ other: ConstraintRelatableTarget) -> ConstraintMakerEditable</code> 与 <code>equalToSuperview</code> 的来源。核心方法是 <code>relatedTo(_ other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable</code>,返回 ConstraintMakerEditable 类型的实例 ConstraintMakerEditable(继承 ConstraintMakerPriortizable) 在设定约束的宽度、高度以及偏移的时候,提供相应的加减乘除方法,返回 ConstraintMakerPriortizable 类型的实例 ConstraintMakerPriortizable(继承 ConstraintMakerFinalizable) 提供方法来设置约束的 priority,返回 ConstraintMakerFinalizable 类型的实例 ConstraintMakerFinalizable 一个只有一个类型为 ConstraintDescription 的属性的类,正如它的类名,有一个 ConstraintMakerFinalizable 实例,就得到了对于一个约束的完整描述。 至此,我们已经知道 SnapKit 是靠什么来确定了三个东西: 谁在做约束(ConstraintView) 怎么做约束(ConstraintMaker) 约束是什么(ConstraintDescription) let aView = UIView() aView.snp.makeConstraints({ make in make.width.equalToSuperview().dividedBy(2).priority(100) }) 当我们写下这样的语句时,先忽略掉 <code>snp</code> 是什么不管,里面设定 aView 的宽度为它的父视图的一半的这行约束语句,执行了这样的逻辑: ConstraintMaker 提供 <code>makeConstraints</code> 方法来让我们写约束的同时,开始维护了一个 ConstraintDescription 数组,叫 <code>descriptions</code> make 本身是 ConstraintMaker 类型的 在我们写下 <code>.width</code> 时,<code>descriptions</code> 数组第一次加入内容(<code>self.description</code>),同时我们用这个内容生成了一个 ConstraintMakerRelatable 实例 在我们写下 <code>.equalToSuperview()</code> 时,上一步中的内容(<code>self.description</code>)继续添加信息,同时我们用它生成了一个 ConstraintMakerEditable 实例 之后的 <code>.dividedBy(2).priority(100)</code> 使得之前的 ConstraintMakerEditable 实例变成了一个 ConstraintMakerFinalizable 实例,这个实例的 description 属性的类型是 ConstraintDescription,它包含了我们所描述的全部内容。但由于 ConstraintMakerEditable 本身就继承自 ConstraintMakerFinalizable,所以 <code>.dividedBy(2).priority(100)</code> 这一部分即便不写,这条语句在语法上也已经完成。 做个总结:到这里我们发现 ConstraintMaker 以及和它相关的类,构造了一套 DSL 来让我们可以轻松地写出约束语句,而这些语句把信息都放到了一个 ConstraintDescription 实例(<code>self.description</code>)里面,但我们仍然不知道它是如何以 UIKit 里面的 NSLayoutConstraint 的形式作用的。 snp 是什么 SnapKit 里面存在这样一些东西: <code>public protocol ConstraintDSL {}</code> <code>public protocol ConstraintBasicAttributesDSL : ConstraintDSL {}</code> <code>public protocol ConstraintAttributesDSL : ConstraintBasicAttributesDSL {}</code> <code>public struct ConstraintViewDSL: ConstraintAttributesDSL {}</code> 上面我们知道了 <code>aView</code> 作为一个 UIView,它同时也就是一个 ConstraintView,ConstraintView 有一个 snp 的属性,这给我们提供了入口来通过 SnapKit 给任意的 UIView 或 AppKit 里面的 NSView 通过 <code>.snp</code> 这样的语法来写约束。 这个 snp 属性的类型就是结构体 ConstraintViewDSL 一看就是面向协议的写法,通过一个个的 extension 来给 protocol 添加功能,最后用 struct 实现出来,就有了 snp 这个属性。 let topView = UIView() let centerView = UIView() centerView.snp.makeConstraints({ make in make.top.equalTo(topView.snp.bottom).offset(16) }) 这段代码展现了 snp 的两个作用: snp 有 left top right bottom edges size 等一大堆属性,这些属性的类型是 ConstraintItem,这是用于构造约束位置关系的 snp 作为 ConstraintViewDSL,有 <code>prepareConstraints</code> <code>makeConstraints</code> <code>remakeConstraints</code> <code>updateConstraints</code> <code>removeConstraints</code> 等函数,我们最常用的是 <code>makeConstraints</code> ,传入一个 closure,在里面写约束关系。这里要注意,我们使用的 <code>makeConstraints</code> 方法来源于 ConstraintViewDSL,但真正实现了构造约束的其实是我们上文里面写的 ConstraintMaker 里面的 <code>makeConstraints</code> 方法,见图: 约束是如何作用的 到现在我们还是没说,从 snp 到 ConstraintMaker,再到 ConstraintMakerFinalizable 的 description 属性,到底哪里创建了 NSLayoutConstraint,答案其实在之前提过多次的 ConstraintMaker 里面 // public class ConstraintMaker internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { let maker = ConstraintMaker(item: item) closure(maker) var constraints: [Constraint] = [] for description in maker.descriptions { guard let constraint = description.constraint else { continue } constraints.append(constraint) } for constraint in constraints { constraint.activateIfNeeded(updatingExisting: false) } } internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) { guard item.constraints.count > 0 else { self.makeConstraints(item: item, closure: closure) return } let maker = ConstraintMaker(item: item) closure(maker) var constraints: [Constraint] = [] for description in maker.descriptions { guard let constraint = description.constraint else { continue } constraints.append(constraint) } for constraint in constraints { constraint.activateIfNeeded(updatingExisting: true) } } 我们传入一个闭包来写约束关系时,这个闭包给叫做 maker 的 ConstraintMaker 实例写入了信息,遍历 maker 的 descriptions 之后(我们之前说一条约束语句最终得到一个 self.description,但往往会有多条约束,所以 ConstraintMakerFinalizable 里面的 self.description,在 ConstraintMaker 里被一个数组维护),我们得到了 Constraint 数组。 Constraint 这个类还没有介绍过,不过上面这个核心方法加上以前的内容,已经可以让我们猜出来,约束是怎么写出来的了: 其他内容补充 1 随便写了两句,展示一下各个方法传入的参数的类型,发现有各种 Target,貌似很复杂,不过点开之后发现是这种景象: 说白了就是因为 <code>equalTo:</code> 这个方法里面能传的参数类型比较多,手动来一个一个限制一下,我们看到 ConstraintRelatableTarget 这里可以放一些原生的可以代表数字的类型,外加四个自定义的 Constraint 类型。其他的 Target 协议也差不多是这种情况。 个人觉得这种做法还是挺值得学习的。 其他内容补充 2 SnapKit 里面用来表示位置主体的类其实不是 ConstraintView,而是 ConstraintItem 我们管这个“主体”叫 target,一个 target,再加上一个 ConstraintAttributes 实例,就可以组成一个 ConstraintItem。 有 attributes 属性很好理解,因为比如我们去做对齐,可以是 aView 的 top 和 bView 的 bottom 对齐,而不能是 aView 和 bView 对齐。但是为什么 target 的类型是 AnyObject 而不是 ConstraintView,即 UIView 或 NSView 呢? 在 ConstraintViewDSL 里面,target 确实是 ConstraintView 类型, 但在 ConstraintLayoutSupportDSL 里面,target 是 ConstraintLayoutSupport 类型, 在 ConstraintLayoutGuideDSL 里面,target 是 ConstraintLayoutGuide 类型 这部分就不具体解释了,想一探究竟的去看 LayoutConstraintItem.swift 这个文件吧。

优秀的个人博客,低调大师

iOS视频裁剪小工具——VideoTailor

最近在写swift,顺便写个小工具练练手。VideoTailor是对AVFoundation框架的封装,可以方便的裁剪视频区域以及时长,并允许指定输出视频的码率等参数。 0x00 如何使用 VideoTailor使用很简单,只暴露了export()方法对应的几个重载方法。使用时必须指定AVAsset视频对象,以及文件输出路径。 如果只想裁剪视频时长,可以调用export(_ asset: AVAsset, _ timeRange: CMTimeRange, _ outputUrl: URL)方法,参数timeRange表示需要裁剪的时间区间。 如果想裁剪一块视频区域,并指定视频输出分辨率,可以调用export(_ asset: AVAsset, _ rect: CGRect, _ outputSize: CGSize, _ outpu

优秀的个人博客,低调大师

iOS自动检测版本更新

虽然苹果官方是不允许应用自动检测更新,提示用户下载,因为苹果会提示你有多少个软件需要更新,但是有的时候提示用户一下有新版还是很有必要的。 首先说一下原理: 每个上架的苹果应用程序,都会有一个应用程序的ID,根据这个ID我们就可以获取到当前程序的最新版本号,然后和自己的版本号作比较,如果一样的话就是最新版,反之就不是新版,就可以提示用户来手动下载最新版的程序。因为有ID所以就可以定位到这个APP,点击下载即可。 源码: 一般建议检测更新的代码放到主页控制器里。 首先还要导入一个头文件用来打开AppStore下载更新 //AppStore #import <StoreKit/StoreKit.h> 接着还有代理 SKStoreProductViewControllerDelegate 然后开始检测更新 //检测版本,版本更新 NSError *error; NSString *urlStr = @"http://itunes.apple.com/lookup?id=上架AppID"; NSURL *url = [NSURL URLWithString:urlStr]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSDictionary *appInfoDict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error]; if (error) { return; } NSArray *resultArray = [appInfoDict objectForKey:@"results"]; if (![resultArray count]) { return; } NSDictionary *infoDict = [resultArray objectAtIndex:0]; //获取服务器上应用的最新版本号 NSArray* arr=[infoDict[@"version"] componentsSeparatedByString:@"."]; NSInteger updateVersion=0; for (int i=0; i<arr.count; i++) { if(i==0) { updateVersion+=[arr[i] integerValue]*1000; } else if (i==1) { updateVersion+=[arr[i] integerValue]*100; } else if (i==2) { updateVersion+=[arr[i] integerValue]*10; } else if (i==3) { updateVersion+=[arr[i] integerValue]*1; } } NSString *trackName = infoDict[@"trackName"]; _trackViewUrl = infoDict[@"trackViewUrl"]; //获取当前设备中应用的版本号 NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary]; NSArray* arr2=[[infoDic objectForKey:@"CFBundleShortVersionString"] componentsSeparatedByString:@"."]; NSInteger currentVersion=0; for (int i=0; i<arr2.count; i++) { if(i==0) { currentVersion+=[arr2[i] integerValue]*1000; } else if (i==1) { currentVersion+=[arr2[i] integerValue]*100; } else if (i==2) { currentVersion+=[arr2[i] integerValue]*10; } else if (i==3) { currentVersion+=[arr2[i] integerValue]*1; } } //判断两个版本是否相同 if (currentVersion < updateVersion) { NSString *titleStr = [NSString stringWithFormat:@"检查更新:%@", trackName]; NSString *messageStr = [NSString stringWithFormat:@"发现新版本%@,是否更新", infoDict[@"version"]]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:titleStr message:messageStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"升级", nil]; //为了区分其他弹出框而已 alert.tag = 1112427256; [alert show]; } 接着就是用户更不更的问题了 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (alertView.tag == 1112427256) { if (buttonIndex == 1) { //点击”升级“按钮,就从打开app store上应用的详情页面 SKStoreProductViewController *storeProductVC = [[SKStoreProductViewController alloc] init]; storeProductVC.delegate = self; NSDictionary *dict = [NSDictionary dictionaryWithObject:@"上架AppID" forKey:SKStoreProductParameterITunesItemIdentifier]; [storeProductVC loadProductWithParameters:dict completionBlock:^(BOOL result, NSError *error) { if (result) { [self presentViewController:storeProductVC animated:YES completion:nil]; } }]; } } } 还有就是用户打开AppStore但是没有下载就返回回来的状况 - (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController { [viewController dismissViewControllerAnimated:YES completion:nil]; } OK到这里就结束了。这样的话就可以检测App是不是最新版了,而且用户也能实时看到,最关键的是苹果审核还能通过。

优秀的个人博客,低调大师

Ios生产证书申请(含推送证书)

一、Mac机上生成请求文件。 Mac机上点击证书助手 => 从证书颁发机构请求证书 => 得到CertificateSigningRequest.certSigningRequest请求文件(此请求证书建议一直保存,因为根证书的生成需要使用此请求文件,根证书多个app可以使用一个)。 二、创建“根证书”,多应用可以使用一个。 (如果之前已经生成了根证书,并且你有此前保存的请求文件CertificateSigningRequest.certSigningRequest,此项可以忽略,直接使用之前的证书。) 点击Certificates => Production 右上角点击添加按钮,右边主内容选择Production => App Store and Ad Hoc,我们把这个证书姑且称为“根证书”,如图: 三、创建App IDs,每个app拥有自己的证书。 点击Identifiers => App IDs 右上角点击添加按钮,沟中推送选项,点击上传开发、生成证书的请求文件,如图: 四、创建推送证书,每个app拥有自己的证书。 点击Certificates => Production 右上角点击添加按钮,右边主内容选择Production => Apple Push Notification service SSL (Sandbox & Production),点击下一步选择上一步创建的appid,点击下一步上次第一步的请求证书,即可创建成功。 五、创建描述文件Provisioning Profiles文件,每个app拥有自己的证书。 点击Provisioning Profiles => Distribution 右上角点击添加按钮,右边主内容选择Distribution => App Store选择第二步的appid,点击继续按钮选择你第二步创建的根证书,点击继续按钮填写name即可创建完成。 附加知识: 1.所有的xx.p12文件都是用你创建的根证书或者是推送证书xx.cer文件,在mac机器上使用钥匙串工具生成的。 2.极光推送需要上传的证书为,开发推送证书+生成推送证书生成导出的xx.p12文件,加导p12时候输入的口令密码。 3.deviceone打包生产证书需要,根证书/推送证书 + 描述文件。(根证证书/推送证书)和App Ids创建的时候请求文件(CertificateSigningRequest.certSigningRequest)必须一样。 总结:也就是说如果不需要添加推送证书的前提下,证书是不需要重新申请证书的,只需要使用之前的根证书+新创建的App IDs即可,生成描述文件,从而打包和上传App。 《完》 如果本文对你有所帮助,请打赏——1元就足够感动我:) 联系邮箱:intdb@qq.com 我的GitHub: https://github.com/vipstone 关注公众号: 作者: 王磊 出处: http://vipstone.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,请标明出处。

优秀的个人博客,低调大师

【iOS 开发】用泛型简化 instantiateViewController

使用 storyboard 的时候,我们经常会写出下面这样的代码,用来跳转到其他页面 if let editVC = self.storyboard?.instantiateViewController(withIdentifier: "EditVC") as? EditVC { self.navigationController?.pushViewController(editVC, animated: true) } 最多改成这样 guard let editVC = self.storyboard?.instantiateViewController(withIdentifier: "EditVC") as? EditVC else { return } 实在是太冗长了,简化第一步,或许我们可以直接将 <code>EditVC</code> 这个类型字符串化变成 <code>"EditVC"</code>,代码变成: guard let editVC = self.storyboard?.instantiateViewController(withIdentifier: String(describing: EditVC.self)) as? EditVC else { return } 嗯,更长了,但是既然 <code>EditVC</code> 使用了两次,这使得我们有机会把这个过程封装成一个函数,而 <code>EditVC</code> 是唯一需要传递的参数 func instantiateVC(vc:UIViewController) -> UIViewController? { let id = String(describing: vc.self) return storyboard?.instantiateViewController(withIdentifier: id) } // how to use guard let editVC = instantiateVC(vc: EditVC()) as? EditVC else { return } 封装之后依然尴尬: 因为我们不能确定每次都需要函数返回 <code>EditVC</code> ,所以只能用 <code>UIViewController</code> 当做返回值,这使得我们还需要再加上 <code>as? EditVC</code> 去做类型转换,相当于还是手动使用了两次 <code>EditVC</code> ,而不是一次 传入的参数是 <code>EditVC()</code> 而不是 <code>EditVC</code> ,看起来丑陋 一次解决两个问题的答案是:泛型! 我们在函数中限定泛型 <code>T</code> 为 <code>UIViewController</code> ,但 <code>T</code> 具体是我们的 App 中的哪个子类我们不去管,通过函数的参数来指定 T 的具体类型,随后确定出我们函数的返回值为那个我们指定的 <code>T</code> 最终结果: extension UIViewController { func instantiateVC<T: UIViewController>(type: T.Type) -> T? { let id = String(describing: T.self) return storyboard?.instantiateViewController(withIdentifier: id) as? T } } // how to use guard let editVC = instantiateVC(type: EditVC.self) else { return } 前后对比: // before guard let editVC = storyboard?.instantiateViewController(withIdentifier: "EditVC") as? EditVC else { return } // after guard let editVC = instantiateVC(type: EditVC.self) else { return } 提醒: 这里我假装这个函数回避掉了直接使用字符串去传入 <code>Storyboard ID</code> 的风险,但可以这么做的前提是,这里的 <code>EditVC</code> 到 <code>"EditVC"</code> 可以直接字符串化。 如果你也要这么做的话,至少要保证你的类名的字符串化的结果和你的 <code>Storyboard ID</code> 是有固定关联的。比如 <code>EditVC</code> 对应 <code>"editvc"</code> 或 <code>"EDITVC"</code> 或 <code>"editVC"</code> (这样你只要修改字母大小写就可以了),而不是 <code>"abc123"</code> 这种随便写的东西。

优秀的个人博客,低调大师

iOS开发之城市选择器

城市选择器,借助于UIPickerView来实现,第一列为省份,第二列为第一列省份对应的城市或者区,数据放在plist中,plist结构如下图所示,第一层是一个Dictionary,每个省份对应的城市是一个Array: plist.png 实现步骤 第一步 拖入一个UIPickerView到StoryBoard中,然后设置UIPickerViewDelegate,和UIPickerViewDataSource为当前的控制器,如下图红色区域所示: 设置数据源与代理.png 第二步 在对应的ViewController中进行实现,代码注释非常详细 #import "ViewController.h" @interface ViewController () <UIPickerViewDelegate, UIPickerViewDataSource> /** * plist对应的字典 */ @property (nonatomic, strong) NSDictionary* cityNames; /** * 省份 */ @property (nonatomic, strong) NSArray* provinces; /** * 城市 */ @property (nonatomic, strong) NSArray* cities; /** * 选中的省份 */ @property (nonatomic, strong) NSString* selectedProvince; @end @implementation ViewController /** * 懒加载plist * * @return plist对应的字典 */ - (NSDictionary*)cityNames { if (_cityNames == nil) { NSString* path = [[NSBundle mainBundle] pathForResource:@"cityData" ofType:@"plist"]; _cityNames = [NSDictionary dictionaryWithContentsOfFile:path]; } return _cityNames; } /** * 懒加载省份 * * @return 省份对应的数组 */ - (NSArray*)provinces { if (_provinces == nil) { //将省份保存到数组中 但是字典保存的是无序的 所以读出来的省份也是无序的 _provinces = [self.cityNames allKeys]; } return _provinces; } - (void)viewDidLoad { [super viewDidLoad]; //设置默认选中的省份是provinces中的第一个元素 self.selectedProvince = self.provinces[0]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /** * 返回每一列的行数 * * @param pickerView * @param component * * @return */ - (NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component { if (component == 0) { return self.provinces.count; } else { self.cities = [self.cityNames valueForKey:self.selectedProvince]; return self.cities.count; } } /** * 返回每一行显示的文本 * * @param pickerView * @param row * @param component * * @return */ - (NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { //第一列返回所有的省份 if (component == 0) { return self.provinces[row]; } else { self.cities = [self.cityNames valueForKey:self.selectedProvince]; return self.cities[row]; } } /** * 一共多少咧 * * @param pickerView * * @return */ - (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView { return 2; } /** * 选中某一行后回调 联动的关键 * * @param pickerView * @param row 用户选择的省份 * @param component */ - (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if (component == 0) { //选中的省份 self.selectedProvince = self.provinces[row]; //重新加载第二列的数据 [pickerView reloadComponent:1]; //让第二列归位 [pickerView selectRow:0 inComponent:1 animated:YES]; } } @end 实现效果 城市选择器.gif 附件 plist文件下载地址:http://pan.baidu.com/s/1dETRthZ

优秀的个人博客,低调大师

iOS - Quartz 2D 画板绘制

1、绘制画板 1.1 绘制简单画板 PaintBoardView.h @interface PaintBoardView : UIView @end PaintBoardView.m @interface PaintBoardView () /// 路径 @property (nonatomic, strong) UIBezierPath *path; /// 保存所有路径的数组 @property (nonatomic, strong) NSMutableArray *pathsArrayM; @end @implementation PaintBoardView /// 初始化 - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { self.backgroundColor = [UIColor whiteColor]; } return self; } /// 触摸开始 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { // 获取触摸起始点位置 CGPoint startPoint = [touches.anyObject locationInView:self]; // 添加路径描绘起始点 [self.path moveToPoint:startPoint]; // 添加一条触摸路径描绘 [self.pathsArrayM addObject:self.path]; } /// 触摸移动 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { // 获取触摸点位置 CGPoint touchPoint = [touches.anyObject locationInView:self]; // 添加路径描绘 [self.path addLineToPoint:touchPoint]; // 刷新视图 [self setNeedsDisplay]; } /// 触摸结束 - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { // 获取绘制结果 UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0); CGContextRef ctx = UIGraphicsGetCurrentContext(); [self.layer renderInContext:ctx]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData *data = UIImagePNGRepresentation(image); [data writeToFile:@"/Users/JHQ0228/Desktop/Images/pic.png" atomically:YES]; } /// 触摸取消 - (void)touchesCancelled:(NSSet *)touches withEvent:(nullable UIEvent *)event { [self touchesEnded:touches withEvent:event]; } /// 绘制图形 - (void)drawRect:(CGRect)rect { for (UIBezierPath *path in self.pathsArrayM) { // 绘制路径 [path stroke]; } } /// 懒加载 - (UIBezierPath *)path { if (_path == nil) { _path = [UIBezierPath bezierPath]; } return _path; } - (NSMutableArray *)pathsArrayM { if (_pathsArrayM == nil) { _pathsArrayM = [NSMutableArray array]; } return _pathsArrayM; } @end ViewController.m // 创建画板 CGRect frame = CGRectMake(20, 50, self.view.bounds.size.width - 40, 200); PaintBoardView *paintBoard = [[PaintBoardView alloc] initWithFrame:frame]; [self.view addSubview:paintBoard]; 效果 1.2 绘制画板封装 具体实现代码见 GitHub 源码 QExtension QPaintBoardPath.h @interface QPaintBoardPath : UIBezierPath /// 线的颜色 @property (nonatomic, strong) UIColor *pathColor; /// 线的宽度 @property (nonatomic, assign) CGFloat pathWidth; @end QPaintBoardPath.m @implementation QPaintBoardPath @end QPaintBoardView.h @interface QPaintBoardView : UIView /// 画线的宽度,default is 1,max is 30 @property (nonatomic, assign) CGFloat paintLineWidth; /// 画笔的颜色,default is blackColor @property (nonatomic, strong) UIColor *paintLineColor; /// 画板的颜色,default is whiteColor @property (nonatomic, strong) UIColor *paintBoardColor; /** * 创建画板视图控件,获取绘画结果 * * @param frame 画板视图控件 frame * @param lineWidth 画笔的线宽,default is 1,max is 30 * @param lineColor 画笔的颜色,default is blackColor * @param boardColor 画板的颜色,default is whiteColor * @param result 绘画结果 * * @return 手势锁视图控件 */ + (instancetype)q_paintBoardViewWithFrame:(CGRect)frame lineWidth:(CGFloat)lineWidth lineColor:(nullable UIColor *)lineColor boardColor:(nullable UIColor *)boardColor paintResult:(void (^)(UIImage * _Nullable image))result; /** * 创建简单画板视图控件 * * @param frame 画板视图控件 frame * * @return 手势锁视图控件 */ + (instancetype)q_paintBoardViewWithFrame:(CGRect)frame; /** * 获取绘画结果 * * @return 绘画结果图片 */ - (UIImage * _Nullable)q_getPaintImage; /** * 清除绘画结果 */ - (void)q_clear; /** * 撤销绘画结果 */ - (void)q_back; @end QPaintBoardView.m #import "QPaintBoardPath.h" @interface QPaintBoardView () /// 路径 @property (nonatomic, strong, nullable) QPaintBoardPath *path; /// 保存所有路径的数组 @property (nonatomic, strong) NSMutableArray *pathsArrayM; /// 绘画结果 @property (nonatomic, copy) void (^resultBlock)(UIImage * _Nullable); /// 按钮工具条 @property (nonatomic, strong) UIView *toolView; /// 画笔设置视图 @property (nonatomic, strong) UIView *brushSetingView; /// 颜色选择视图 @property (nonatomic, strong) UIScrollView *colorSelectedView; /// 画板设置视图 @property (nonatomic, strong) UIScrollView *boardSetingView; /// 记录线的颜色 @property (nonatomic, strong) UIColor *lastPaintLineColor; /// 记录线的宽度 @property (nonatomic, assign) CGFloat lastPaintLineWidth; @end @implementation QPaintBoardView #pragma mark - 创建画板 /// 创建画板视图控件,获取绘画结果 + (instancetype)q_paintBoardViewWithFrame:(CGRect)frame lineWidth:(CGFloat)lineWidth lineColor:(nullable UIColor *)lineColor boardColor:(nullable UIColor *)boardColor paintResult:(void (^)(UIImage * _Nullable image))result { QPaintBoardView *paintBoardView = [[self alloc] init]; // CGRect tmpFrame = frame; // tmpFrame.size.height = frame.size.height + 44; paintBoardView.frame = frame; paintBoardView.paintLineWidth = (lineWidth > 30 ? 30 : lineWidth) ? : 1; paintBoardView.paintLineColor = lineColor ? : [UIColor blackColor]; paintBoardView.paintBoardColor = boardColor ? : [UIColor whiteColor]; paintBoardView.resultBlock = result; return paintBoardView; } /// 创建简单画板视图控件 + (instancetype)q_paintBoardViewWithFrame:(CGRect)frame { QPaintBoardView *paintBoardView = [[self alloc] initWithFrame:frame]; paintBoardView.paintLineWidth = 1; paintBoardView.paintLineColor = [UIColor blackColor]; paintBoardView.paintBoardColor = [UIColor whiteColor]; return paintBoardView; } #pragma mark - 自定义画板 /// 初始化,自定义画板界面 - (instancetype)init { if (self = [super init]) { self.clipsToBounds = YES; // 添加工具按钮视图 self.toolView = [[UIView alloc] init]; self.toolView.backgroundColor = [UIColor blackColor]; [self addSubview:self.toolView]; NSArray *imageNames = @[@"btn_brush", @"btn_board", @"btn_eraser", @"btn_back", @"btn_clear", @"btn_save"]; NSArray *selectedImageNames = @[@"btn_brush_pressed", @"btn_board_pressed", @"btn_eraser_pressed"]; for (NSUInteger i = 0; i < 6; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.tag = i; [button setBackgroundImage:[self q_getBundleImageWithName:imageNames[i]] forState:UIControlStateNormal]; [button addTarget:self action:@selector(toolButtonClick:) forControlEvents:UIControlEventTouchUpInside]; [self.toolView addSubview:button]; if (i < 3) { [button setBackgroundImage:[self q_getBundleImageWithName:selectedImageNames[i]] forState:UIControlStateSelected]; } } // 添加画笔设置视图 self.brushSetingView = [[UIView alloc] init]; self.brushSetingView.backgroundColor = [UIColor grayColor]; [self addSubview:self.brushSetingView]; [self sendSubviewToBack:self.brushSetingView]; UIView *widthBackView = [[UIView alloc] init]; widthBackView.layer.borderWidth = 1; widthBackView.layer.borderColor = [UIColor lightGrayColor].CGColor; UIView *widthView = [[UIView alloc] init]; [widthBackView addSubview:widthView]; [self.brushSetingView addSubview:widthBackView]; UISlider *widthSlider = [[UISlider alloc] init]; widthSlider.thumbTintColor = [UIColor orangeColor]; [widthSlider addTarget:self action:@selector(widthSliderClick:) forControlEvents:UIControlEventValueChanged]; [self.brushSetingView addSubview:widthSlider]; UIButton *colorSelectedBtn = [[UIButton alloc] init]; colorSelectedBtn.layer.borderWidth = 1; colorSelectedBtn.layer.borderColor = [UIColor lightGrayColor].CGColor; [colorSelectedBtn addTarget:self action:@selector(colorSelectedBtnClick:) forControlEvents:UIControlEventTouchUpInside]; [self.brushSetingView addSubview:colorSelectedBtn]; // 添加画笔颜色选择视图 self.colorSelectedView = [[UIScrollView alloc] init]; self.colorSelectedView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.3]; self.colorSelectedView.showsHorizontalScrollIndicator = NO; [self addSubview:self.colorSelectedView]; [self sendSubviewToBack:self.colorSelectedView]; NSArray *colorArray = @[[UIColor blackColor], [UIColor whiteColor], [UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor cyanColor], [UIColor magentaColor], [UIColor orangeColor], [UIColor yellowColor], [UIColor darkGrayColor], [UIColor lightGrayColor], [UIColor brownColor], [UIColor grayColor], [UIColor purpleColor]]; for (NSUInteger i = 0; i < 14; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.layer.borderWidth = 1; button.layer.borderColor = [UIColor lightGrayColor].CGColor; [button setBackgroundColor:colorArray[i]]; [button addTarget:self action:@selector(colorSelectedClick:) forControlEvents:UIControlEventTouchUpInside]; [self.colorSelectedView addSubview:button]; } // 添加画板设置视图 self.boardSetingView = [[UIScrollView alloc] init]; self.boardSetingView.backgroundColor = [UIColor grayColor]; self.boardSetingView.showsHorizontalScrollIndicator = NO; [self addSubview:self.boardSetingView]; [self sendSubviewToBack:self.boardSetingView]; for (NSUInteger i = 0; i < 14; i++) { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.layer.borderWidth = 1; button.layer.borderColor = [UIColor lightGrayColor].CGColor; [button setBackgroundColor:colorArray[i]]; [button addTarget:self action:@selector(boardColorSelectedClick:) forControlEvents:UIControlEventTouchUpInside]; [self.boardSetingView addSubview:button]; } } return self; } /// 布局子控件 - (void)layoutSubviews { [super layoutSubviews]; if (self.subviews.count) { // 设置工具按钮视图 self.toolView.frame = CGRectMake(0, self.bounds.size.height - 44, self.bounds.size.width, 44); for (NSUInteger i = 0; i < 6; i++) { CGFloat margin = (self.bounds.size.width - 44 * 6) / 7; CGFloat x = margin + (margin + 44) * i; self.toolView.subviews[i].frame = CGRectMake(x, 0, 44, 44); } // 设置画笔设置视图 self.brushSetingView.frame = CGRectMake(0, self.bounds.size.height - 44, self.bounds.size.width, 60); self.brushSetingView.subviews[0].frame = CGRectMake(15, 15, 30, 30); self.brushSetingView.subviews[0].layer.cornerRadius = 15; self.brushSetingView.subviews[0].layer.masksToBounds = YES; CGFloat w = self.paintLineWidth; self.brushSetingView.subviews[0].subviews[0].frame = CGRectMake(15 - w / 2, 15 - w / 2, w, w); self.brushSetingView.subviews[0].subviews[0].layer.cornerRadius = w / 2; self.brushSetingView.subviews[0].subviews[0].layer.masksToBounds = YES; self.brushSetingView.subviews[0].subviews[0].backgroundColor = self.paintLineColor; self.brushSetingView.subviews[1].frame = CGRectMake(60, 15, self.bounds.size.width - 60 - 80, 32); UISlider *slider = self.brushSetingView.subviews[1]; slider.value = self.paintLineWidth / 30; self.brushSetingView.subviews[2].frame = CGRectMake(self.bounds.size.width - 60, 15, 50, 30); self.brushSetingView.subviews[2].backgroundColor = self.paintLineColor; // 设置画笔颜色选择视图 self.colorSelectedView.frame = CGRectMake(0, self.bounds.size.height - 44, self.bounds.size.width, 60); self.colorSelectedView.contentSize = CGSizeMake(14 * (50 + 20) + 20, 50); for (NSUInteger i = 0; i < 14; i++) { CGFloat x = 20 + (20 + 50) * i; self.colorSelectedView.subviews[i].frame = CGRectMake(x, 10, 50, 40); } // 设置画板设置视图 self.boardSetingView.frame = CGRectMake(0, self.bounds.size.height - 44, self.bounds.size.width, 60); self.boardSetingView.contentSize = CGSizeMake(14 * (50 + 20) + 20, 50); for (NSUInteger i = 0; i < 14; i++) { CGFloat x = 20 + (20 + 50) * i; self.boardSetingView.subviews[i].frame = CGRectMake(x, 10, 50, 40); } } } /// 工具按钮点击事件处理 - (void)toolButtonClick:(UIButton *)btn { switch (btn.tag) { case 0: { // 画笔设置 [self exitEraseState]; if (btn.isSelected == NO) { [self hideBoardSetingView]; [self showColorSelectedView]; [self showBrushSetingView]; } else { [self hideColorSelectedView]; [self hideBrushSetingView]; } break; } case 1: { // 画板设置 [self exitEraseState]; if (btn.isSelected == NO) { [self hideColorSelectedView]; [self hideBrushSetingView]; [self showBoardSetingView]; } else { [self hideBoardSetingView]; } break; } case 2: { // 擦除 [self hideBoardSetingView]; [self hideColorSelectedView]; [self hideBrushSetingView]; if (btn.selected == NO) { [self enterEraseState]; } else { [self exitEraseState]; } break; } case 3: { // 撤销 [self hideBoardSetingView]; [self hideColorSelectedView]; [self hideBrushSetingView]; [self q_back]; break; } case 4: { // 清除 [self hideBoardSetingView]; [self hideColorSelectedView]; [self hideBrushSetingView]; [self exitEraseState]; [self q_clear]; break; } case 5: { // 获取绘制结果 [self hideBoardSetingView]; [self hideColorSelectedView]; [self hideBrushSetingView]; [self exitEraseState]; if (self.resultBlock) { self.resultBlock([self q_getPaintImage]); } break; } default: break; } } /// 画笔线宽设置按钮点击事件处理 - (void)widthSliderClick:(UISlider *)slider { if (slider.value == 0) { self.paintLineWidth = 1; } else { self.paintLineWidth = slider.value * 30; } CGFloat w = self.paintLineWidth; self.brushSetingView.subviews[0].subviews[0].frame = CGRectMake(15 - w / 2, 15 - w / 2, w, w); self.brushSetingView.subviews[0].subviews[0].layer.cornerRadius = w / 2; } /// 画笔颜色选择按钮点击事件处理 - (void)colorSelectedBtnClick:(UIButton *)btn { if (btn.selected == NO) { [self showColorSelectedView]; } else { [self hideColorSelectedView]; } } /// 画笔颜色选择点击响应事件处理 - (void)colorSelectedClick:(UIButton *)btn { self.paintLineColor = btn.backgroundColor; self.brushSetingView.subviews[0].subviews[0].backgroundColor = btn.backgroundColor; self.brushSetingView.subviews[2].backgroundColor = btn.backgroundColor; } /// 画板颜色选择点击响应事件处理 - (void)boardColorSelectedClick:(UIButton *)btn { self.paintBoardColor = btn.backgroundColor; } /// 显示画笔设置视图 - (void)showBrushSetingView { UIButton *setBrushBtn = self.toolView.subviews[0]; if (setBrushBtn.selected == NO) { setBrushBtn.selected = YES; [UIView animateWithDuration:0.2 animations:^{ CGRect frame = CGRectMake(0, self.bounds.size.height - 44 - 60, self.bounds.size.width, 60); self.brushSetingView.frame = frame; }]; } } /// 隐藏画笔设置视图 - (void)hideBrushSetingView { UIButton *setBrushBtn = self.toolView.subviews[0]; if (setBrushBtn.selected) { setBrushBtn.selected = NO; [UIView animateWithDuration:0.2 animations:^{ CGRect frame = CGRectMake(0, self.bounds.size.height - 44, self.bounds.size.width, 60); self.brushSetingView.frame = frame; }]; } } // 显示画笔颜色选择视图 - (void)showColorSelectedView { UIButton *colorSelectedBtn = self.brushSetingView.subviews[2]; if (colorSelectedBtn.selected == NO) { colorSelectedBtn.selected = YES; [UIView animateWithDuration:0.2 animations:^{ CGRect frame = CGRectMake(0, self.bounds.size.height - 44 - 60 - 60, self.bounds.size.width, 60); self.colorSelectedView.frame = frame; }]; } } /// 隐藏画笔颜色选择视图 - (void)hideColorSelectedView { UIButton *colorSelectedBtn = self.brushSetingView.subviews[2]; if (colorSelectedBtn.selected) { colorSelectedBtn.selected = NO; [UIView animateWithDuration:0.2 animations:^{ CGRect frame = CGRectMake(0, self.bounds.size.height - 44, self.bounds.size.width, 60); self.colorSelectedView.frame = frame; }]; } } /// 显示画板设置视图 - (void)showBoardSetingView { UIButton *setBoardBtn = self.toolView.subviews[1]; if (setBoardBtn.selected == NO) { setBoardBtn.selected = YES; [UIView animateWithDuration:0.2 animations:^{ CGRect frame = CGRectMake(0, self.bounds.size.height - 44 - 60, self.bounds.size.width, 60); self.boardSetingView.frame = frame; }]; } } /// 隐藏画板设置视图 - (void)hideBoardSetingView { UIButton *setBoardBtn = self.toolView.subviews[1]; if (setBoardBtn.selected) { setBoardBtn.selected = NO; [UIView animateWithDuration:0.2 animations:^{ CGRect frame = CGRectMake(0, self.bounds.size.height - 44, self.bounds.size.width, 60); self.boardSetingView.frame = frame; }]; } } /// 进入擦除状态 - (void)enterEraseState { UIButton *setEraseBtn = self.toolView.subviews[2]; if (setEraseBtn.selected == NO) { setEraseBtn.selected = YES; self.lastPaintLineColor = self.paintLineColor; self.paintLineColor = self.paintBoardColor; self.lastPaintLineWidth = self.paintLineWidth; self.paintLineWidth = self.paintLineWidth + 5; } } /// 退出擦除状态 - (void)exitEraseState { UIButton *setEraseBtn = self.toolView.subviews[2]; if (setEraseBtn.isSelected) { setEraseBtn.selected = NO; self.paintLineColor = self.lastPaintLineColor; self.paintLineWidth = self.lastPaintLineWidth; } } #pragma mark - 绘制图案 /// 触摸开始 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { if (self.subviews.count) { [self hideColorSelectedView]; [self hideBrushSetingView]; [self hideBoardSetingView]; } // 获取触摸起始点位置 CGPoint startPoint = [touches.anyObject locationInView:self]; // 添加路径描绘起始点 [self.path moveToPoint:startPoint]; // 记录线的属性 self.path.pathColor = self.paintLineColor; self.path.pathWidth = self.paintLineWidth; // 添加一条触摸路径描绘 [self.pathsArrayM addObject:self.path]; } /// 触摸移动 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { // 获取触摸点位置 CGPoint touchPoint = [touches.anyObject locationInView:self]; // 添加路径描绘 [self.path addLineToPoint:touchPoint]; // 刷新视图 [self setNeedsDisplay]; } /// 触摸结束 - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event { // 销毁 path self.path = nil; } /// 触摸取消 - (void)touchesCancelled:(NSSet *)touches withEvent:(nullable UIEvent *)event { [self touchesEnded:touches withEvent:event]; } /// 绘制图形,只要调用 drawRect 方法就会把之前的内容全部清空 - (void)drawRect:(CGRect)rect { for (QPaintBoardPath *path in self.pathsArrayM) { // 绘制路径 path.lineWidth = path.pathWidth; [path.pathColor setStroke]; path.lineCapStyle = kCGLineCapRound; path.lineJoinStyle = kCGLineJoinRound; [path stroke]; } } /// 获取绘画结果 - (UIImage * _Nullable)q_getPaintImage { UIImage *image = nil; CGSize boardSize = self.bounds.size; if (self.subviews.count) { boardSize.height = self.bounds.size.height - 44; } if (self.pathsArrayM.count) { UIGraphicsBeginImageContextWithOptions(boardSize, NO, 0); CGContextRef ctx = UIGraphicsGetCurrentContext(); [self.layer renderInContext:ctx]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); } return image; } /// 清除绘画结果 - (void)q_clear { if (self.pathsArrayM.count) { [self.pathsArrayM removeAllObjects]; [self setNeedsDisplay]; } } /// 撤销绘画结果 - (void)q_back { if (self.pathsArrayM.count) { [self.pathsArrayM removeLastObject]; [self setNeedsDisplay]; } } /// 懒加载 - (QPaintBoardPath * _Nullable)path { // path 每次绘制完成后需要销毁,否则无法清除之前绘制的路径 if (_path == nil) { _path = [QPaintBoardPath bezierPath]; } return _path; } - (NSMutableArray *)pathsArrayM { if (_pathsArrayM == nil) { _pathsArrayM = [NSMutableArray array]; } return _pathsArrayM; } /// 设置属性值 - (void)setPaintBoardColor:(UIColor *)paintBoardColor { _paintBoardColor = paintBoardColor; self.backgroundColor = paintBoardColor; } /// 加载 bundle 中的图片 - (UIImage *)q_getBundleImageWithName:(NSString *)name { NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"QPaintBoardView.bundle"]; UIImage *image = [[UIImage imageWithContentsOfFile:[bundlePath stringByAppendingPathComponent:name]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; return image; } @end 1、创建简单画板 // 创建简单画板 CGRect frame = CGRectMake(20, 50, self.view.bounds.size.width - 40, 200); QPaintBoardView *paintBoardView = [QPaintBoardView q_paintBoardViewWithFrame:frame]; // 可选属性值设置 paintBoardView.paintLineWidth = 5; // default is 1 paintBoardView.paintLineColor = [UIColor redColor]; // default is blackColor paintBoardView.paintBoardColor = [UIColor cyanColor]; // default is whiteColor [self.view addSubview:paintBoardView]; self.paintBoardView = paintBoardView; // 撤销绘画结果 [self.paintBoardView q_back]; // 清除绘画结果 [self.paintBoardView q_clear]; // 获取绘画结果 UIImage *image = [self.paintBoardView q_getPaintImage]; 效果 2、创建画板 // 创建画板 QPaintBoardView *paintBoard = [QPaintBoardView q_paintBoardViewWithFrame:self.view.bounds lineWidth:0 lineColor:nil boardColor:nil paintResult:^(UIImage * _Nullable image) { if (image) { NSData *data = UIImagePNGRepresentation(image); [data writeToFile:@"/Users/JHQ0228/Desktop/Images/pic.png" atomically:YES]; } }]; [self.view addSubview:paintBoard]; 效果

优秀的个人博客,低调大师

SwipeListView实现仿ios的侧滑

github地址:https://github.com/xiangzhihong/SwipeMenuListView 今天介绍一个SwipeMenuListView实现侧滑删除的例子,其实和listview的用法一样,就是多了创建删除等view的步骤,然后通过addview添加到父布局中。 效果如果: 当然你也也可以根据自己的需要增加更多的自定义View。 直接看代码吧: Add dependency dependencies { compile 'com.baoyz.swipemenulistview:library:1.3.0' } Step 1 add SwipeMenuListView in layout xml <com.baoyz.swipemenulistview.SwipeMenuListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> Step 2 create a SwipeMenuCreator to add items. SwipeMenuCreator creator = new SwipeMenuCreator() { @Override public void create(SwipeMenu menu) { // create "open" item SwipeMenuItem openItem = new SwipeMenuItem( getApplicationContext()); // set item background openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE))); // set item width openItem.setWidth(dp2px(90)); // set item title openItem.setTitle("Open"); // set item title fontsize openItem.setTitleSize(18); // set item title font color openItem.setTitleColor(Color.WHITE); // add to menu menu.addMenuItem(openItem); // create "delete" item SwipeMenuItem deleteItem = new SwipeMenuItem( getApplicationContext()); // set item background deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25))); // set item width deleteItem.setWidth(dp2px(90)); // set a icon deleteItem.setIcon(R.drawable.ic_delete); // add to menu menu.addMenuItem(deleteItem); } }; // set creator listView.setMenuCreator(creator); Step 3 listener item click event listView.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(int position, SwipeMenu menu, int index) { switch (index) { case 0: // open break; case 1: // delete break; } // false : close the menu; true : not close the menu return false; } }); Swipe directions // Right mListView.setSwipeDirection(SwipeMenuListView.DIRECTION_RIGHT); // Left mListView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT); Create Different Menu Use the ViewType of adapter class AppAdapter extends BaseAdapter { ... @Override public int getViewTypeCount() { // menu type count return 2; } @Override public int getItemViewType(int position) { // current menu type return type; } ... } Create different menus depending on the view type SwipeMenuCreator creator = new SwipeMenuCreator() { @Override public void create(SwipeMenu menu) { // Create different menus depending on the view type switch (menu.getViewType()) { case 0: // create menu of type 0 break; case 1: // create menu of type 1 break; ... } } }; 大家可以把代码fork下来,自行修改优化

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码