你如何管理你的 iOS 项目中的视图标签? [英] How do you manage view tags in your iOS project?

查看:24
本文介绍了你如何管理你的 iOS 项目中的视图标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 iOS 应用程序,它使用了一些带有大量元素的视图控制器.我在界面构建器中(在故事板中)构建了视图控制器.对于某些关键元素(登录按钮、重要文本等),我创建了一个 IBOutlet 以便能够在我的代码中使用这些元素(主要调整文本/图形).
对于其他一些我只需要快速修复(例如我以编程方式显示和隐藏的活动指示器)的其他人,我选择不创建 IBOutlet,而是给它们一个标签编号并通过 viewWithTag 访问它们:(NSInteger) 方法.

I have an iOS app that uses a few viewcontrollers with lots of elements. I built the viewcontrollers in the interface builder (in a storyboard). For some key elements (loginbutton, important text, etc..) I created an IBOutlet to be able to use these elements in my code (adjust text/graphics mostly).
For some others where I just needed a quick fix (for example an activity indicator that I show and hide programmatically), I chose to not create an IBOutlet, but instead give them a tag number and access them by the viewWithTag:(NSInteger) method.

这似乎对我有用(这只是我的第二个 iOS 项目,因此这样做可能完全错误).但是现在视图控制器变得更加复杂,我发现很难记住我已经用于标签的数字.除了遍历所有元素并检查它们的标签之外,还有什么方法可以跟踪这一点?

This seemed to work for me (it's only my second iOS project so it might be completely wrong to do this). But now that the viewcontrollers get more complex I find it hard to remember which numbers I already used for tags. Is there any way to keep track of this other than by going trough all the elements and checking their tag?

也许以这种方式使用标签是错误的,在那种情况下也可以.我可以将它们全部查找一次,然后为我现在使用标签的所有情况创建 IBOutlets.

Maybe it's all wrong to use tags this way, in that case that's fine too. I could look them all up once and just create IBOutlets for all the cases where I use a tag now.

推荐答案

我会尽量避免使用view tags.

通过使用属性数据模型而不是标签,总有其他(而且几乎总是更好)的方法来做完全相同的事情.

There are always other (and almost always better) ways to do exactly the same thing by using properties and data models instead of tags.

这是我找到的一篇文章,其中有一些很好的例子说明为什么它们不是一个好主意... http://doing-it-wrong.mikeweller.com/2012/08/youre-doing-it-wrong-4-uiview.html

Here is an article that I found with some nice examples of why they're not a good idea to use... http://doing-it-wrong.mikeweller.com/2012/08/youre-doing-it-wrong-4-uiview.html

如果您需要访问一个 UI 元素,请在需要它的类的界面中为它创建一个 IBOutlet.

If you need to access a UI element then create an IBOutlet for it in the interface of the class that needs it.

或者,如果有多个相同的元素,那么您可以创建一个 IBOutletCollection,它只是一个包含链接到它的所有元素的数组.

Alternatively, if there are several elements that are the same then you can create and IBOutletCollection which is just an array that contains all the elements linked to it.

编辑

对于现在遇到这个问题的任何人.这是一位前 Apple 工程师的文章,解释了为什么使用标签不仅是一种代码异味和不良做法,而且是一个性能问题.

For anyone stumbling across this now. This is an article from a former Apple engineer explaining why using tags is not only a code smell and bad practice but also a performance issue.

https://www.fadel.io/blog/posts/ios-performance-tips-you-probably-didnt-know/

这篇关于你如何管理你的 iOS 项目中的视图标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆