loading...

CS193p Notes - Lecture 5: ViewBuilder + Shape + ViewModifier

lankinen profile image Lankinen ・2 min read

Access control

  • private doesn't allow anyone outside the struct/class access it
  • private(set) means that setting is private but reading is not meaning that anyone can read it

ViewBuilder (12:05)

@ViewBuilder can be added to any function that returns a view. If there is a list of views it combines them into one.

"The contents of a @ViewBuilder is a list of Views. No need to type return. Cannot use vars.

@ViewBuilder
func front(of card: Card) -> some View {
  RoundedRectangle(cornerRadius: 10)
  RoundedRectangle(cornerRadius: 10).stroke()
  Text(card.content)
}

Shape (20:22)

CG = Core Graphics

import SwiftUI

struct Pie: Shape {
  var startAngle: Angle
  var endAngle: Angle
  var clockwise: Bool = false

  func path(in rect: CGRect) -> Path {
    let center = CGPoint(x: react.midX, y: react.midY)
    let radius = min(rect.width, rect.height) / 2
    let start = CGPoint(
      x: center.x + radius * cos(CGFloat(startAngle.radians)),
      y: center.y + radius * sin(CGFloat(startAngle.radians))
    )

    var p = Path()
    p.move(to: center)
    p.addLine(to: start)
    p.addArc(
      center: center,
      radius: radius,
      startAngle: startAngle,
      endAngle: endAngle,
      clockwise: clockwise
    )
    p.addLine(to: center)
    return p
}
  • 0 degrees is to right
  • 0x0 is in left top corner and increases by going down and right

ViewModifier (41:54)

  • There are two things that can be animated: shapes and views.
  • Animating views happens in ViewModifier
  • Modifier can for example make any view to look like a card, cardify
Text("Ghost").modifier(Cardify(isFaceUp: true))

struct Cardify: ViewModifier {
  var isFaceUp: Bool
  func body(content: Content) -> some View {
    ZStack {
      if isFaceUp {
        RoundedRectangle(cornerRadius: 10).fill(Color.white)
        RoundedRectangle(cornerRadius: 10).stroke()
        content
      } else {
        RoundedRectangle(cornerRadius: 10)
      }
    }
  }
}
Text("Ghost").cardify(isFaceUp: true)

extension View {
  func cardify(isFaceUp: Bool) -> some View {
    return self.modifier(Cardify(isFaceUp: isFaceUp))
  }
}

@RealLankinen

Originally published here

Posted on by:

Discussion

pic
Editor guide