原文地址:链接描述
在这篇文章中有一个简单的项目叫 BeginnerCook Starter ,其中一个ViewController+.swift的文件中有这样一段代码:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if listView.subviews.count < herbs.count {
listView.viewWithTag(0)?.tag = 1000 //prevent confusion when looking up images
setupList()
}
}
listView.viewWithTag(0)?.tag = 1000 这一行代码到底有什么作用,他虽然加了注释我也不是很明白,求大神回答。
He later uses tags starting from 0 to identify each
UIIamgeView
, so he needs to change the tag of the view that is 0 in the listView (the type isUIScrollView
) to avoid following Tags added later are repeated.UIIamgeView
,所以需要把 listView(类型是个UIScrollView
) 中为 0 的 view 的 tag 改掉,避免跟后面自己添加的 tag 重复。原来下面的分析没说清,思路有误但结论是对的,我的锅,抱歉抱歉!更新如下:
总分总结构:原来的结论没错,tag 从 0 改到 1000 的 view 就是那个横滚动条,但思路错了。。。虽然答案中没表现出来,但还是详细补充一下
先写两个从文档能了解到的内容:
swift 中的
tag
声明是这样的:var tag: Int
并且文档下面有这段:这里可以看出,tag 的类型不是 optional ,说明
UIView
一定有tag,讨论中指出默认值是 0 。题中的界面现在是这样的:
注释 1 :对的。。。他在 StoryBoard 里设置了 listView 的 tag 为 1000 ,如下图。横滚动条因为在 StoryBoard 里不好设置 tag ,就没在这改。记住这个,马上用到。
(右下角的 tag = 1000)
然后
- viewWithTag:
的文档中有下面这段This method searches the current view and all of its subviews for the specified view.
`viewWithTag:` 方法会查找 这个 view 本身 和它的 subviews 。
上文提到 listView 的 tag 已经在 StoryBoard 里改成了 1000 ,因此执行题目中
listview.viewWithTag(0)
It turns out that the analysis below is not clear. The thinking is wrong but the conclusion is correct. It’s my fault. I’m sorry! Updated as follows:
Total score and structure: The original conclusion is correct. The view whose tag is changed from 0 to 1000 is the horizontal scroll bar, but the idea is wrong. . . Although it is not shown in the answer, I will add it in detail First write two things that can be learned from the document:
The
tag
declaration in swift is like this:var tag: Int
and there is this paragraph below the document: The default value is 0. You can set the value of this tag and use that value to identify the view later.It can be seen here that the type of tag is not optional, which means that
UIView
must have a tag. The discussion pointed out that the default value is 0.The interface in the question now looks like this:
(tag in the lower right corner = 1000)
Then the document of
- viewWithTag:
contains the following paragraph DiscussionThis method searches the current view and all of its subviews for the specified view.
The 🎜`viewWithTag:` method will look for the view itself and its subviews. 🎜 🎜As mentioned above, the tag of listView has been changed to 1000 in StoryBoard. Therefore, when executinglistview.viewWithTag(0)
in the question, the first thing found is not the listView itself, but the ones in its subviews. scrollbar. Then change the scroll bar’s tag to 1000🎜 🎜So back to the previous conclusion, the view with tag 0 is it: 🎜 🎜🎜🎜🎜🎜 🎜🎜🎜🎜🎜 🎜Horizontal scroll bar XD. . . 🎜 🎜 🎜My expression ability is limited. . . It's such a simple thing that I almost feel dizzy. Or give me an example: 🎜 🎜🎜🎜🎜🎜🎜🎜🎜🎜 🎜Playground code in the picture: 🎜 rrreee