iOS:父视图覆盖的子视图阴影
Posted
技术标签:
【中文标题】iOS:父视图覆盖的子视图阴影【英文标题】:iOS: Shadow of subview covered by parent view 【发布时间】:2020-06-25 07:10:30 【问题描述】:我有一个包含子视图的视图。我希望子视图有一个阴影,而不是被父视图覆盖。如果父视图是透明的,则此方法有效,但如果它不是阴影的一部分,则被它覆盖。我尝试设置子视图的zPosition,但没有成功。
它是这样的:
这是我的代码,您可以将其复制粘贴到 Playground 中:
import UIKit
import PlaygroundSupport
import UIKit
class MyViewController : UIViewController
override func loadView()
let view = UIView()
view.backgroundColor = .white
let myView = MyView(frame: .init(x: 30,
y: 30,
width: 200,
height: 200))
view.addSubview(myView)
self.view = view
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
class MyView: UIView
let upper = UIView()
override init(frame: CGRect)
super.init(frame: frame)
commonInit()
required init?(coder: NSCoder)
super.init(coder: coder)
commonInit()
private func commonInit()
upper.backgroundColor = .red
upper.translatesAutoresizingMaskIntoConstraints = false
addSubview(upper)
NSLayoutConstraint.activate([
upper.topAnchor.constraint(equalTo: topAnchor),
upper.leadingAnchor.constraint(equalTo: leadingAnchor),
upper.trailingAnchor.constraint(equalTo: trailingAnchor),
upper.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.8)
])
self.backgroundColor = .yellow
layer.shadowColor = UIColor.blue.cgColor
layer.shadowOpacity = 1
layer.shadowOffset = .zero
layer.shadowRadius = 5
// desperate attempts
upper.layer.zPosition = 1
upper.layer.masksToBounds = false
layer.masksToBounds = false
bringSubviewToFront(upper)
override func layoutSubviews()
super.layoutSubviews()
layer.shadowPath = UIBezierPath(rect: upper.frame).cgPath
【问题讨论】:
【参考方案1】:如果你想让子视图有阴影 .. 像这样将阴影应用到子视图
upper.layer.shadowColor = UIColor.blue.cgColor
upper.layer.shadowOpacity = 1
upper.layer.shadowOffset = .zero
upper.layer.shadowRadius = 5
从这段代码中你得到的是这个
如果我弄错了,请告诉我,您还需要其他东西……我也会尽力帮助您解决问题
【讨论】:
以上是关于iOS:父视图覆盖的子视图阴影的主要内容,如果未能解决你的问题,请参考以下文章