繁体   English   中英

如何在 swift 中仅在 UIVIEW 的顶部和底部添加阴影

[英]How to add shadow only to top and bottom to UIVIEW in swift

我是 swift 的新手,我正在尝试为 UIView 添加阴影。 我的代码是这样的

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) 

但它给四面八方增加了阴影

在此处输入图像描述

我怎样才能添加这样的阴影

一种解决方案是将您的ViewPay放入容器 UIView 中。

将您的ViewPay设置为容器视图的前缘和后缘,并为顶部和底部添加一些填充以显示阴影。

还将容器视图clipsToBounds设置为 true。

我希望能帮助您解决问题。 如果您想要一些简单易懂的东西,并遵循提示。 您创建一个大容器并添加所需的视图。 紫色的垂直视图,另一个灰色的水平视图,中间放一个图像,就像我在代码中所做的那样:


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.

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