Skip to content

Instantly share code, notes, and snippets.

@dedeexe
Created November 6, 2015 10:30
Show Gist options
  • Save dedeexe/f9e6816793f84007c2aa to your computer and use it in GitHub Desktop.
Save dedeexe/f9e6816793f84007c2aa to your computer and use it in GitHub Desktop.
Creating a custom focus view for tvOS
//
// FocusView.swift
// CustomNavigation
//
// Creating a CustomFocusView
// This code shows how to implement a custom view that can be focused in tvOS
// Just set this class as an UIView's custom class
//
import UIKit
class CustomFocusView: UIView {
//Now This View controller can get Focus
override func canBecomeFocused() -> Bool {
return true
}
//We Can chance the focus behavior.... Is a good idea if we evidence it
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
//Bahavior we will trigger when view lost focus
if context.previouslyFocusedView === self
{
UIView.animateWithDuration(0.1, animations: { () -> Void in
context.previouslyFocusedView?.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
}
//Bahavior we will trigger when view get focus
if context.nextFocusedView === self
{
UIView.animateWithDuration(0.1, animations: { () -> Void in
context.nextFocusedView?.transform = CGAffineTransformMakeScale(1.2, 1.2)
})
}
}
}
@PratheeshDBennet
Copy link

Swift 3.x and above version,

```
import UIKit
class CustomFocusView: UIView {

  override var canBecomeFocused: Bool {
      return true
  }
  override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    //Bahavior we will trigger when view lost focus
    if context.previouslyFocusedView === self
    {
      UIView.animate(withDuration: 0.1, animations: { () -> Void in
        context.previouslyFocusedView?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
        })
    }
    
    //Bahavior we will trigger when view get focus
    if context.nextFocusedView === self
    {
      UIView.animate(withDuration: 0.1, animations: { () -> Void in
        context.nextFocusedView?.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
        })
    }
  }
}
```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment