首页 > 关于iOS中viewWithTag的问题?

关于iOS中viewWithTag的问题?

原文地址:链接描述
在这篇文章中有一个简单的项目叫 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 这一行代码到底有什么作用,他虽然加了注释我也不是很明白,求大神回答。


他后面用从 0 开始的 tag 来标识每个 UIIamgeView ,所以需要把 listView(类型是个 UIScrollView) 中为 0 的 view 的 tag 改掉,避免跟后面自己添加的 tag 重复。


原来下面的分析没说清,思路有误但结论是对的,我的锅,抱歉抱歉!更新如下:

总分总结构:原来的结论没错,tag 从 0 改到 1000 的 view 就是那个横滚动条,但思路错了。。。虽然答案中没表现出来,但还是详细补充一下


先写两个从文档能了解到的内容:

swift 中的 tag 声明是这样的: var tag: Int 并且文档下面有这段:

Discussion
The default value is 0. You can set the value of this tag and use that value to identify the view later.

这里可以看出,tag 的类型不是 optional ,说明 UIView 一定有tag,讨论中指出默认值是 0 。

题中的界面现在是这样的:

listView(UIScrollView): tag == 1000 // 1
  |-横滚动条(UIView): tag == 0

注释 1 :对的。。。他在 StoryBoard 里设置了 listView 的 tag 为 1000 ,如下图。横滚动条因为在 StoryBoard 里不好设置 tag ,就没在这改。记住这个,马上用到。

(右下角的 tag = 1000)

然后 - viewWithTag: 的文档中有下面这段

Discussion

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) 时,最先找到的不是 listView 自己,而是它 subviews 中的滚动条。然后把滚动条的 tag 改成 1000

所以回到了之前的结论,那个 tag 为 0 的 view 就是它:

横滚动条啊 XD 。。。


我的表达能力有限。。。很简单的东西,自己都快绕晕了。还是举例子适合我:


图中 Playground 代码:

import UIKit

let viewA = UIView(frame: CGRect(x: 0,y: 0,width: 30,height: 30))
let viewB = UIView(frame: CGRect(x: 0,y: 0,width: 20,height: 20))
viewA.backgroundColor = UIColor.darkGrayColor()
viewB.backgroundColor = UIColor.greenColor()
viewA.addSubview(viewB)

viewA
viewB

viewA.tag // 0 为了截图方便,不预览了
viewB.tag // 0 为了截图方便,不预览了

viewA.viewWithTag(0) // 现在获取到 viewA 自己

viewA.tag = 1000     // StroyBoard 中设置了 tag 为 1000
viewA.viewWithTag(0) // 获取到 viewB

viewA.viewWithTag(0)?.tag = 1000 // 把 viewB 的 tag 也改成 1000
viewA.viewWithTag(0) // 这时结果时 nil

// setupList()
let imageView0 = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
imageView0.backgroundColor = UIColor.redColor()
viewA.addSubview(imageView0)
viewA

viewA.viewWithTag(0) // 拿到了想要的 iamgeView0
【热门文章】
【热门文章】