简体   繁体   English

向UITableViewCell添加开关:故事板与代码

[英]Adding a switch to UITableViewCell: storyboard vs code

I want to add a UISwitch to my settings view controller. 我想将UISwitch添加到我的设置视图控制器中。 The switch looks identically to Airplane Mode toggle in the 'Settings' app on iOS. 该开关的外观与iOS上“设置”应用中的“飞行模式”切换相同。 I'm not sure about what is the best way to implement this. 我不确定实现此目标的最佳方法是什么。

I am choosing between: 我选择:

  1. adding a UISwitch in code 在代码中添加UISwitch
  2. creating a custom cell in the Storyboard and creating an outlet for a switch 在情节提要中创建自定义单元并为开关创建插座

Here's my Swift code for adding a switch to UITableViewCell: 这是我的Swift代码,用于向UITableViewCell添加开关:

let soundSwitch = UISwitch(frame: CGRectZero)
soundSwitch.addTarget(self, action: "test:", forControlEvents: UIControlEvents.ValueChanged)
// I created an outlet for the cell that will contain a switch
soundCell.accessoryView = tickingSoundSwitch

What are advantages and disadvantages of using these solutions? 使用这些解决方案的优缺点是什么?

My suggestion is to use either 我的建议是使用

1.UISwitch in storyboard along with an IBAction , if you use this approach things becomes easy ,you need not to add target and mess with lot of codes. 1.UISwitch和IBAction一起放在情节提要中 ,如果使用这种方法,事情变得容易了,您无需添加目标,也不必添加很多代码。

or 要么

2.Completely rely on code , Using this approach your UISwitch will not get tight coupled with storyboard's UI. 2.完全依赖代码 ,使用这种方法,您的UISwitch不会与情节提要的UI紧密结合。 Even in the future if you want to change the UI stuffs in storyboard you need not to do any changes for your UISWitch ,ie you don't need to attach all those IBAction and outlet stuffs as you are using pure code based approach(provided your UISwitch requirement doesn't change). 即使在将来,如果您想更改情节提要中的UI内容,也无需为UISWitch进行任何更改,即,您无需使用基于纯代码的方法附加所有这些IBAction和插座内容(前提是您提供UISwitch要求不变)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM