[英]How to add shadow only to top and bottom to UIVIEW in swift
I am new in swift and I am trying to add shadow to UIView.我是 swift 的新手,我正在尝试为 UIView 添加阴影。 My code is like this
我的代码是这样的
ViewPay.layer.masksToBounds = false
ViewPay.layer.shadowRadius = 2
ViewPay.layer.shadowOpacity = 1
ViewPay.layer.shadowColor = UIColor.red.cgColor
ViewPay.layer.shadowOffset = CGSize(width: 0 , height:2)
but it is adding shadow to all side但它给四面八方增加了阴影
How can I add shadow like this我怎样才能添加这样的阴影
One solution is, put your ViewPay
inside a container UIView.一种解决方案是将您的
ViewPay
放入容器 UIView 中。
Set your ViewPay
to leading and trailing edges of container view, and for top and bottom add some padding to show shadow.将您的
ViewPay
设置为容器视图的前缘和后缘,并为顶部和底部添加一些填充以显示阴影。
Also set container view clipsToBounds
equals to true.还将容器视图
clipsToBounds
设置为 true。
I hope to help with the solution of your question.我希望能帮助您解决问题。 In case you wanted something simple to understand, and also following the tips.
如果您想要一些简单易懂的东西,并遵循提示。 You create a large container and add the required views.
您创建一个大容器并添加所需的视图。 A vertical view of the purple color, another horizontal that would be gray color and in the middle put an image, as I did in the code:
紫色的垂直视图,另一个灰色的水平视图,中间放一个图像,就像我在代码中所做的那样:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Big container
let container = UIView(frame: CGRect(x: self.view.bounds.width * 0.25, y: self.view.bounds.height * 0.5, width: 250, height: 290))
container.backgroundColor = .clear
self.view.addSubview(container)
//Purple view
let viewContainer = UIView(frame: CGRect(x: container.bounds.midX , y: 0, width: container.bounds.width * 0.89, height: container.bounds.height))
viewContainer.layer.anchorPoint.x = 1.0
viewContainer.backgroundColor = UIColor(displayP3Red: 158/255, green: 131/255, blue: 178/255, alpha: 1.0)
viewContainer.layer.cornerRadius = 8
viewContainer.clipsToBounds = true
container.addSubview(viewContainer)
//Gray view
let viewContainer2 = UIView(frame: CGRect(x: container.bounds.midX , y: container.bounds.midY, width: container.bounds.width * 0.93, height: container.bounds.height * 0.86))
viewContainer2.layer.anchorPoint.y = 1.0
viewContainer2.layer.anchorPoint.x = 1.0
viewContainer2.backgroundColor = UIColor(white: 0.5, alpha: 0.3)
viewContainer2.layer.cornerRadius = 5
viewContainer2.clipsToBounds = true
container.addSubview(viewContainer2)
//image
let imageView = UIImageView(frame: CGRect(x: container.bounds.midX, y: container.bounds.midY, width: container.bounds.width * 0.90, height: container.bounds.height * 0.90))
imageView.contentMode = .scaleToFill
imageView.layer.anchorPoint = CGPoint(x: 1.0, y: 1.0)
imageView.layer.cornerRadius = 10
imageView.clipsToBounds = true
imageView.image = UIImage(named: "image name")
container.addSubview(imageView)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.