简体   繁体   中英

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

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. (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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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