简体   繁体   English

获取UIStackView中的第一个UIButton

[英]Get the first UIButton in a UIStackView

I'm working on my view and I'm having an issue with getting a shadow around a button within the stack view. 我正在处理我的视图,但在堆栈视图中的按钮周围出现阴影时遇到问题。 Most of the work I have done has been within the storyboard directly. 我所做的大部分工作都直接在情节提要中进行。

故事板渲染显示背景

模拟器渲染缺少的背景

Here is the method I am using to apply the shadow to the view 这是我用来将阴影应用于视图的方法

func addShadow(to view: UIView) {
    view.layer.shadowColor = shadowColor
    view.layer.shadowOpacity = shadowOpacity
    view.layer.shadowOffset = shadowOffset
    if let bounds = view.subviews.first?.bounds {
        view.layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    }

    view.layer.shouldRasterize = true
}

and this is how I'm finding the button within the view from ViewController.swift 这就是我从ViewController.swift在视图中查找按钮的方式

for subview in self.view.subviews {
    if subview.isKind(of: UIButton.self) && subview.tag == 1 {
        addShadow(to: subview)
    }
}

I know the problem stems from the stack view and the UIView inside of the stack view that holds the button. 我知道问题源于堆栈视图和包含按钮的堆栈视图内部的UIView。 (self.view > UIStackView > UIView > [UIButton, UILabel]) (self.view> UIStackView> UIView> [UIButton,UILabel])

I know I could do this with recursion in the for-loop but I'm trying to be a little more precise to optimize performance and would prefer to add the shadows in one shot. 我知道我可以在for-loop使用递归来做到这一点,但我正在尝试更加精确地优化性能,并且希望一次添加阴影。

You have a few options: 您有几种选择:

  1. add the shadow in the storyboard itself 在情节提要中添加阴影
  2. add an outlet to the button, then add shadow in code 在按钮上添加插座,然后在代码中添加阴影
  3. add the button to a collection, then enumerate over the collection adding shadows 将按钮添加到集合中,然后枚举集合中的阴影
  4. recursively add the shadows (this isn't going to hit performance nearly as hard as you're thinking, adding the shadows hurts performance more than doing this recursively) 递归地添加阴影(这不会像您想的那样严重影响性能,添加阴影比递归地增加对性能的损害更大)

You are correct in that the button is a view on the stack view, so your for loop doesn't hit the button directly to add a shadow to it. 您是正确的,因为该按钮是堆栈视图上的一个视图,因此您的for循环不会直接点击该按钮来为其添加阴影。

The easiest way to solve this is by far the recursive way, or something like this: 解决此问题的最简单方法是到目前为止的递归方法,或类似这样的方法:

func addShadowsTo(subviews: [UIView]) {
    for subview in subviews {
        if subview.isKind(of: UIButton.self) && subview.tag == 1 {
            addShadow(to: subview)
        }

        if let stackView = subview as? UIStackView {
            addShadowToSubviews(subviews: stackView.subviews)
        }
    }
}

func viewDidload() {
    super.viewDidLoad()

    addShadowsTo(subviews: view.subviews)
}

If you want some instructions on how to do any of the other ways, just comment. 如果您想获得有关其他方法的一些说明,只需评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM