Custom Controls in iOS - Part 3: Interaction and UI | Ray Wenderlich

Learn about the interaction options available for custom controls, enable user interaction on the Deluxe Button, and test in a playground live view.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4433-custom-controls-in-ios/lessons/3
deluxeButton.unpressedBackgroundColor = #colorLiteral(
  red: 0.98, green: 0.85, blue: 0.55, alpha: 1
)
deluxeButton.pressedBackgroundColor = #colorLiteral(
  red: 0.72, green: 0.89, blue: 0.6, alpha: 1
)

You can’t do above steps until you changing deluxeButton from let to var.

When running this with Xcode 9 beta / Swift 4, it appears the UIKit internal implementation of how UIStackView handles hiding/unhiding elements has changed. When the label unhides, it descends from the top of the stackView instead of rising from the bottom.

To combat this, I’ve changed the animate behavior to instead change the constant of the constraint.

  fileprivate var labelHeightConstraint: NSLayoutConstraint!

in initPhase2():

labelHeightConstraint = label.heightAnchor.constraint(equalToConstant: frame.height / 3)
private func animate(isPressed: Bool) {
    let (duration, backgroundColor, constant) = { isPressed ? (duration: 0.05, backgroundColor: pressedBackgroundColor, constant: 0) :
      (duration: 0.1, backgroundColor: unpressedBackgroundColor, constant: self.frame.height * 1.0 / 3.0
)
    }()
    
    labelHeightConstraint.constant = constant
    UIView.animate(withDuration: duration) {
      self.layoutIfNeeded()
      self.backgroundColor = backgroundColor
    }
  }