如何使用 NSString 标签识别视图?
view.tag 只存储 NSInteger 值。
那么,如何用 NSString Value 来标识每个视图呢?
不可用?
一些例子:
view0.stringTag = @"basic";
view1.stringTag = @"advanced";
view.tag is only stored NSInteger Value.
so, how to identify each view with NSString Value?
not avaliable?
some example:
view0.stringTag = @"basic";
view1.stringTag = @"advanced";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
UIView
上没有stringTag
属性。如果您需要执行此类操作,您可以在UIView
上使用类别并将标签存储在关联的对象中:There's no
stringTag
property onUIView
. If you need to do this kind of thing you can use a category onUIView
and store the tag in an associated object:不,你不能使用字符串。如果您的目标是代码可读性,则可以使用枚举。不过,请务必从 1 开始枚举,因为 0 是所有视图的默认标记:
No, you can't use a string. If you are aiming for code readability, you could use an enum. Be sure to start your enum from 1, though, as 0 is the default tag for all views:
使用
恢复标识符
。Use
restorationIdentifier
.它不被直接支持。当然,您可以创建一个 C 数组、NSArray、NSDictionary 或类似的东西来完成此操作(与 int 标签结合使用)。
it's not supported directly. you could of course create a C array, a NSArray, a NSDictionary, or something like that to accomplish this (in conjunction with the int tag).
仅当您使用 stringTag 属性对自己的 UIView 进行子类化时,这才有可能。你这样做的原因是什么?
This is only possible if you subclass your own UIView with a stringTag property. What is your reason for doing this?
迄今为止最简单的解决方案: 链接到我对类似问题的回答< /a>
尝试设置 UIView 的辅助功能标识符属性:
Output =>你的字符串在这里
这行为就像“标签”属性,但允许你使用 NSString
Simplest solution by far: Link to my answer for a similar question
Try setting the accessibility identifier property of your UIView:
Output => your string here
This behaves just like the "tag" property but allows you to use NSString
首先,你永远不会按原样使用标签。总是在 .h 文件中这样做(最佳实践,恕我直言。):
然后,在创建视图时:
然后,在您想要找到视图的位置:
或者,您可以定义一个哈希函数,将 NSString 转换为某个 Integer可以指定为标签。例如
,
我也将其留给您定义哈希函数。
First, you never use tags as it is. Always do it like this possibly in a .h file(best practice, IMHO. ):
Then, when creating views:
Then, where you want to find the view:
Alternatively, you can define a hash function that converts NSString to some Integer that can be assigned as a tag. E.g.
and then also,
I leave it up to you to define the hash function.
如果你想比较 NSStrings,
就像
stringTag 是要在视图中定义的 NSString 变量并分配要比较的值一样
If you want to compare NSStrings,
as like
where stringTag is an NSString variable to be defined in the views and assigned value to compare