【swift学习笔记】五.使用枚举优雅的管理Segue
2023-09-27 14:26:23 时间
在做页面转跳的时候,我们要给Segue命名,如果Segue多了,管理他们就是一个恶梦。我们可以枚举更优雅的管理这些Segue。
1.我们先来建立一个protocol,他的功能就是让实现类实现一个SegueIdentifier别名,这个SegueIdentifier必需为RawRepresentable类型,在后边我们就会用
protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
2.我们要对上边的protocol扩展,并且实现protocol必须为UIViewControl,SegueIdentifier的原值要为String类型
这个扩展有两个方法一个是用要实现的别名来调用执行Segue方法performSegueWithIdentifier。另一个方法segueIdentifierForSegue通过Segue的identifier来得到SegueIdentifier.
extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String { func performSegueWithIdentifier(segueIdentifier: SegueIdentifier, sender: AnyObject) { performSegueWithIdentifier(segueIdentifier.rawValue, sender: sender) } func segueIdentifierForSegue(segue: UIStoryboardSegue) -> SegueIdentifier { guard let identifier = segue.identifier, segueIdentifier = SegueIdentifier(rawValue: identifier) else { fatalError("invalid segue identifier \(segue.identifier)") } return segueIdentifier } }
3.用ViewController实现SegueHandlerType。再用一个枚举来实现SegueIdentifier并且为String,里面有两个case这两个就要我们要打开的新窗体的名称。
下边有两个按钮Action是用SegueIdentifier枚举来打开相应的窗体。
class ViewController: UIViewController, SegueHandlerType { enum SegueIdentifier: String { case ShowView1 case ShowView2 } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func openView1(sender: AnyObject) { performSegueWithIdentifier(.ShowView1, sender: self) } @IBAction func openView2(sender: AnyObject) { performSegueWithIdentifier(.ShowView2, sender: self) } }
4.新建两个新窗体,分别用Segue联接这两个窗体。这两个Segue分别命名为我们的枚举类型的两个值:“ShowView1” “ShowView2”。再来两个Button连接后台的两个窗体的Action
相关文章
- 神经网络与机器学习 笔记—改善反向传播的性能试探法
- iOS安全些许经验和学习笔记
- Memcache 笔记
- 【学习笔记10】JavaScript三元运算符和比较运算符
- [DeeplearningAI笔记]序列模型3.3-3.5集束搜索
- Docker笔记-attach进入容器,退出后容器停止运行
- Go爬虫学习笔记(三)
- 《模式识别》学习笔记(九)判别域界面方程分类和线性判别函数
- [C#] Direct2D 学习笔记 (一)vb.net转换为c#
- Web 在线文件管理器学习笔记与总结(15)剪切文件夹 (16)删除文件夹
- Android学习笔记之网络接口(Http接口,Apache接口,Android接口)
- SQLite学习笔记之软件三个核心流程
- CSS+CSS3 笔记大总结,快来一起复习吧,有你不会的吗
- 高数 | 【17堂课、李林108】自用笔记整理
- PID控制器开发笔记之三:抗积分饱和PID控制器的实现
- Removing the bias of integral pose regression阅读笔记
- 项目笔记:分层模型建立
- 使用Git和TortoiseGit进行程序版本管理学习笔记
- odoo15 使用笔记--库存使用说明
- Linux学习笔记(25)linux批量管理
- Linux学习笔记(23)numa的查看与关闭
- MongoDB学习笔记—权限管理
- 【AI学习笔记】TensorFlow 与 Keras的安装(Windows Anaconda 虚拟环境版)
- kvm虚拟化学习笔记(四)之kvm虚拟机日常管理与配置