无法从 UITabBar 获取 UIImageView swift

Unable to get UIImageView from UITabBar swift

我正在关注 tutorial 以制作标签栏图像的动画。给定的代码行对我不起作用

secondItemView.subviews.first as! UIImageView

因为它获取 UITabBarButtonLabel 类型的数据而不是 UIImageView。 我添加了标签值 1 以便我可以使用标签值获取 UIImageView

secondItemView.viewWithTag(1)

returns 无。获取 UIImageView 引用的另一种方法是什么?

代码

@objc public class MTMainScreenTabsController : UITabBarController {
var secondItemImageView: UIImageView!
public override func viewDidLoad() {
    super.viewDidLoad()
    let secondItemView = self.tabBar.subviews[0]


    print(secondItemView.subviews)
    print(secondItemView.viewWithTag(1))

    //self.secondItemImageView = secondItemView.subviews.secon
    var item: UITabBarItem! = self.tabBar.items![0]


    //self.secondItemImageView = secondItemView.viewWithTag(1) as! UIImageView
}

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

public override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if item.tag == 1 {
        self.secondItemImageView.transform = .identity
        UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
            () -> Void in
                //let rotation = CGAffineTransformMakeRotation(CGFloat(M_PI_2))
            let rotation = CGAffineTransform.init(rotationAngle: CGFloat(Double.pi/2))
                self.secondItemImageView.transform = rotation
        }, completion: nil)
    }
}

}

使用我的代码这个对你有帮助

class AnimatedTabBarController: UITabBarController {

    var secondItemImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondItemView = self.tabBar.subviews[1]
        self.secondItemImageView = secondItemView.subviews.first as! UIImageView
        self.secondItemImageView.contentMode = .center

    }

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

        if item.tag == 1{
            //do our animations

            self.secondItemImageView.transform = CGAffineTransform.identity

            UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: UIViewAnimationOptions(), animations: { () -> Void in

                let rotation = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
                self.secondItemImageView.transform = rotation

                }, completion: nil)
        }
    }  
}

严格依赖子视图的顺序不是一个好习惯,因为它可能会在未来发生变化。如果您确定 secondItemView.subviews 包含 UIImageView 的实例,您可以这样找到它:

let imageView = secondItemView.subviews.flatMap { [=10=] as? UIImageView }.first

一个 imageView 变量将是一个可选的,包含 nil 或一个实际的 UIImageView 如果有任何这种类型的子视图。平面地图将遍历子视图并尝试将每个子视图转换为 UIImageView - 如果失败,结果将被过滤掉,否则它将被放入您要从中获取第一个元素的结果数组中。