[英]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: 您有几种选择:
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.