2016-06-07 12 views
11

Ho cercato ma non sono riuscito a trovare come aggiungere un'ombra interna a UIView, solo in alto (dall'alto verso il basso) per Swift. Qual è il modo migliore di aggiungere la cerchia interna in Swift?Aggiunta di ombreggiatura interna a UIView

Modifica: ho trovato alcune domande & risposte su SO, tuttavia sono in obj-c o sembra così complicato. Stavo solo cercando un modo Swifty di più, se c'è qualche

Quello che voglio ottenere:

enter image description here

+2

Mi ci sono voluti 2 secondi: https://github.com/inamiy/YIInnerShadowView – Arbitur

+0

@gotnull Ho trovato questa domanda, tuttavia non riuscivo a capire come aggiungerlo solo in alto. Anche Arbitur, il tuo link è in ogg-c che non potevo tradurre. Nella sua risposta SO, sembra un pezzo abbastanza complicato di codice e tutti i suoi lati .. Non sta anche usando qualcosa di semplice come 'CGSizeMake', ecco perché volevo chiederlo. Stavo solo cercando un modo Swifty – senty

+1

Se vuoi assicurarti che l'ombra rimanga solo lungo il bordo superiore, non importa il raggio di sfocatura/offset/ecc.e non sanguina negli altri confini, la soluzione migliore è aggiungere "UIImageView' come visualizzazione secondaria, attaccato al bordo superiore e allungato lungo tutta la larghezza. Se hai bisogno di un trattamento speciale ai bordi laterali (come sembra suggerire il tuo screenshot) forse un'immagine elastica con inserti farà il trucco. –

risposta

-2

Usare la seguente libreria:

https://github.com/nlampi/UIView-InnerShadow

// Add a shadow to the top of the view only 
[exampleView addInnerShadowWithRadius:3.0f 
          andColor:[UIColor colorWithWhite:0 alpha:0.45f] 
          inDirection:NLInnerShadowDirectionTop]; 

Ho fatto del mio meglio per convertire l'estensione della libreria in Swift (non è stato verificato, quindi non posso garantire che funzioni). Dovresti farti guidare sulla strada giusta.

import UIKit 

extension UIView { 

    struct NLInnerShadowDirection: OptionSetType { 
     let rawValue: Int 

     static let None = NLInnerShadowDirection(rawValue: 0) 
     static let Left = NLInnerShadowDirection(rawValue: 1 << 0) 
     static let Right = NLInnerShadowDirection(rawValue: 1 << 1) 
     static let Top = NLInnerShadowDirection(rawValue: 1 << 2) 
     static let Bottom = NLInnerShadowDirection(rawValue: 1 << 3) 
     static let All = NLInnerShadowDirection(rawValue: 15) 
    } 

    func removeInnerShadow() { 
     for view in self.subviews { 
      if (view.tag == 2639) { 
       view.removeFromSuperview() 
       break 
      } 
     } 
    } 

    func addInnerShadow() { 
     let c = UIColor() 
     let color = c.colorWithAlphaComponent(0.5) 

     self.addInnerShadowWithRadius(3.0, color: color, inDirection: NLInnerShadowDirection.All) 
    } 

    func addInnerShadowWithRadius(radius: CGFloat, andAlpha: CGFloat) { 
     let c = UIColor() 
     let color = c.colorWithAlphaComponent(alpha) 

     self.addInnerShadowWithRadius(radius, color: color, inDirection: NLInnerShadowDirection.All) 
    } 

    func addInnerShadowWithRadius(radius: CGFloat, andColor: UIColor) { 
     self.addInnerShadowWithRadius(radius, color: andColor, inDirection: NLInnerShadowDirection.All) 
    } 

    func addInnerShadowWithRadius(radius: CGFloat, color: UIColor, inDirection: NLInnerShadowDirection) { 
     self.removeInnerShadow() 

     let shadowView = self.createShadowViewWithRadius(radius, andColor: color, direction: inDirection) 

     self.addSubview(shadowView) 
    } 

    func createShadowViewWithRadius(radius: CGFloat, andColor: UIColor, direction: NLInnerShadowDirection) -> UIView { 
     let shadowView = UIView(frame: CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)) 
     shadowView.backgroundColor = UIColor.clearColor() 
     shadowView.tag = 2639 

     let colorsArray: Array = [ andColor.CGColor, UIColor.clearColor().CGColor ] 

     if direction.contains(.Top) { 
      let xOffset: CGFloat = 0.0 
      let topWidth = self.bounds.size.width 

      let shadow = CAGradientLayer() 
      shadow.colors = colorsArray 
      shadow.startPoint = CGPointMake(0.5, 0.0) 
      shadow.endPoint = CGPointMake(0.5, 1.0) 
      shadow.frame = CGRectMake(xOffset, 0, topWidth, radius) 
      shadowView.layer.insertSublayer(shadow, atIndex: 0) 
     } 

     if direction.contains(.Bottom) { 
      let xOffset: CGFloat = 0.0 
      let bottomWidth = self.bounds.size.width 

      let shadow = CAGradientLayer() 
      shadow.colors = colorsArray 
      shadow.startPoint = CGPointMake(0.5, 1.0) 
      shadow.endPoint = CGPointMake(0.5, 0.0) 
      shadow.frame = CGRectMake(xOffset, self.bounds.size.height - radius, bottomWidth, radius) 
      shadowView.layer.insertSublayer(shadow, atIndex: 0) 
     } 

     if direction.contains(.Left) { 
      let yOffset: CGFloat = 0.0 
      let leftHeight = self.bounds.size.height 

      let shadow = CAGradientLayer() 
      shadow.colors = colorsArray 
      shadow.frame = CGRectMake(0, yOffset, radius, leftHeight) 
      shadow.startPoint = CGPointMake(0.0, 0.5) 
      shadow.endPoint = CGPointMake(1.0, 0.5) 
      shadowView.layer.insertSublayer(shadow, atIndex: 0) 
     } 

     if direction.contains(.Right) { 
      let yOffset: CGFloat = 0.0 
      let rightHeight = self.bounds.size.height 

      let shadow = CAGradientLayer() 
      shadow.colors = colorsArray 
      shadow.frame = CGRectMake(self.bounds.size.width - radius, yOffset, radius, rightHeight) 
      shadow.startPoint = CGPointMake(1.0, 0.5) 
      shadow.endPoint = CGPointMake(0.0, 0.5) 
      shadowView.layer.insertSublayer(shadow, atIndex: 0) 
     } 

     return shadowView 
    } 
} 
+0

Grazie per aver risposto. Devo creare un Bridging Header per questo? C'è un modo per raggiungerlo su Swift? Sarei grato – senty

+0

@senty: Sì, il modo più semplice sarebbe quello di creare un'intestazione di bridging poiché c'è molto codice in Objective-C. – fuzz

+0

Ho esitato a usare l'intestazione del bridging perché ogni volta che provo, continua a rompersi. Se hai tempo, puoi dirmi quali sono i bit necessari per far sì che funzioni perfettamente in Swift? Sarebbe molto utile per tutti – senty

9

Ho utilizzato l'ombreggiatura interna dello strumento su UIView utilizzando Objective-C. Cerco di tradurre il codice in rapido. Ti prego di perdonarmi per il mio povero sintassi rapida

è possibile chiamare la funzione di seguito nella UIView.didMoveToSuperview

func drawShadow() { 
    if nil == self.shadowLayer { 
     let size = self.frame.size 
     self.clipsToBounds = true 
     let layer: CALayer = CALayer() 
     layer.backgroundColor = UIColor.lightGrayColor().CGColor 
     layer.position = CGPointMake(size.width/2, -size.height/2 + 0.5) 
     layer.bounds = CGRectMake(0, 0, size.width, size.height) 
     layer.shadowColor = UIColor.darkGrayColor().CGColor 
     layer.shadowOffset = CGSizeMake(0.5, 0.5) 
     layer.shadowOpacity = 0.8 
     layer.shadowRadius = 5.0 
     self.shadowLayer = layer 

     self.layer.addSublayer(layer) 
    } 
} 
+1

Di gran lunga la migliore risposta. A PARER MIO. Altre risposte usano i gradienti, che non sono le ombre disegnate in Core Graphics. – beyowulf

+0

@beyowulf grazie per aver corretto il mio codice. –

+0

Da dove proviene 'self.shadowLayer'? –

16

Ecco una versione Swift puro che ho scatenato:

public class EdgeShadowLayer: CAGradientLayer { 

    public enum Edge { 
     case Top 
     case Left 
     case Bottom 
     case Right 
    } 

    public init(forView view: UIView, 
       edge: Edge = Edge.Top, 
       shadowRadius radius: CGFloat = 20.0, 
       toColor: UIColor = UIColor.white, 
       fromColor: UIColor = UIColor.black) { 
     super.init() 
     self.colors = [fromColor.cgColor, toColor.cgColor] 
     self.shadowRadius = radius 

     let viewFrame = view.frame 

     switch edge { 
      case .Top: 
       startPoint = CGPoint(x: 0.5, y: 0.0) 
       endPoint = CGPoint(x: 0.5, y: 1.0) 
       self.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: shadowRadius) 
      case .Bottom: 
       startPoint = CGPoint(x: 0.5, y: 1.0) 
       endPoint = CGPoint(x: 0.5, y: 0.0) 
       self.frame = CGRect(x: 0.0, y: viewFrame.height - shadowRadius, width: viewFrame.width, height: shadowRadius) 
      case .Left: 
       startPoint = CGPoint(x: 0.0, y: 0.5) 
       endPoint = CGPoint(x: 1.0, y: 0.5) 
       self.frame = CGRect(x: 0.0, y: 0.0, width: shadowRadius, height: viewFrame.height) 
      case .Right: 
       startPoint = CGPoint(x: 1.0, y: 0.5) 
       endPoint = CGPoint(x: 0.0, y: 0.5) 
       self.frame = CGRect(x: viewFrame.width - shadowRadius, y: 0.0, width: shadowRadius, height: viewFrame.height) 
     } 
    } 

    required public init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 
} 

Per usarlo,

let topShadow = EdgeShadowLayer(forView: targetView, edge: .Top) 
view.layer.addSublayer(topShadow) 

Si noti che il valore predefinito è un gradiente da nero a bianco con una profondità di 20 pixel.

Il codice completo, con un campione UIViewController che consente di attivare o disattivare le ombre su tutti e quattro gli angoli di una vista, è disponibile al numero https://github.com/jrtibbetts/Tenebrae. Ho anche documentato il EdgeShadowLayer abbastanza bene.

3

ho riscritto @NRitH soluzione su Swift 3, anche un po 'refactoring:

final class SideShadowLayer: CAGradientLayer { 
    enum Side { 
     case top, 
     bottom, 
     left, 
     right 
    } 

    init(frame: CGRect, side: Side, shadowWidth: CGFloat, 
     fromColor: UIColor = .black, 
     toColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0), 
     opacity: Float = 0.5) { 
     super.init() 

     colors = [fromColor.cgColor, toColor.cgColor] 
     self.opacity = opacity 

     switch side { 
     case .bottom: 
      startPoint = CGPoint(x: 0.5, y: 1.0) 
      endPoint = CGPoint(x: 0.5, y: 0.0) 
      self.frame = CGRect(x: 0, y: frame.height - shadowWidth, width: frame.width, height: shadowWidth) 

     case .top: 
      startPoint = CGPoint(x: 0.5, y: 0.0) 
      endPoint = CGPoint(x: 0.5, y: 1.0) 
      self.frame = CGRect(x: 0, y: 0, width: frame.width, height: shadowWidth) 

     case .left: 
      startPoint = CGPoint(x: 0.0, y: 0.5) 
      endPoint = CGPoint(x: 1.0, y: 0.5) 
      self.frame = CGRect(x: 0, y: 0, width: shadowWidth, height: frame.height) 

     case .right: 
      startPoint = CGPoint(x: 1.0, y: 0.5) 
      endPoint = CGPoint(x: 0.0, y: 0.5) 
      self.frame = CGRect(x: frame.width - shadowWidth, y: 0, width: shadowWidth, height: frame.height) 
     } 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 
} 
0

Ho aggiornato @ risposta di NRitH e fece un prolungamento fuori di esso anche modificato in modo che è possibile manipolare bordi multipli in una sola volta

utilizzo

myview.addShadow(to: [.top,.bottom], radius: 15.0)

extension UIView{ 

    func addShadow(to edges:[UIRectEdge], radius:CGFloat){ 

     let toColor = UIColor(colorLiteralRed: 235.0/255.0, green: 235.0/255.0, blue: 235.0/255.0, alpha: 1.0) 
     let fromColor = UIColor(colorLiteralRed: 188.0/255.0, green: 188.0/255.0, blue: 188.0/255.0, alpha: 1.0) 
     // Set up its frame. 
     let viewFrame = self.frame 
     for edge in edges{ 
      let gradientlayer   = CAGradientLayer() 
      gradientlayer.colors  = [fromColor.cgColor,toColor.cgColor] 
      gradientlayer.shadowRadius = radius 

      switch edge { 
      case UIRectEdge.top: 
       gradientlayer.startPoint = CGPoint(x: 0.5, y: 0.0) 
       gradientlayer.endPoint = CGPoint(x: 0.5, y: 1.0) 
       gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: gradientlayer.shadowRadius) 
      case UIRectEdge.bottom: 
       gradientlayer.startPoint = CGPoint(x: 0.5, y: 1.0) 
       gradientlayer.endPoint = CGPoint(x: 0.5, y: 0.0) 
       gradientlayer.frame = CGRect(x: 0.0, y: viewFrame.height - gradientlayer.shadowRadius, width: viewFrame.width, height: gradientlayer.shadowRadius) 
      case UIRectEdge.left: 
       gradientlayer.startPoint = CGPoint(x: 0.0, y: 0.5) 
       gradientlayer.endPoint = CGPoint(x: 1.0, y: 0.5) 
       gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height) 
      case UIRectEdge.right: 
       gradientlayer.startPoint = CGPoint(x: 1.0, y: 0.5) 
       gradientlayer.endPoint = CGPoint(x: 0.0, y: 0.5) 
       gradientlayer.frame = CGRect(x: viewFrame.width - gradientlayer.shadowRadius, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height) 
      default: 
       break 
      } 
      self.layer.addSublayer(gradientlayer) 
     } 

    } 

    func removeAllSublayers(){ 
     if let sublayers = self.layer.sublayers, !sublayers.isEmpty{ 
      for sublayer in sublayers{ 
       sublayer.removeFromSuperlayer() 
      } 
     } 
    } 

} 

Shadow

Problemi correlati