3

I've set a custom border to the layer of UITextField. When UITextField is focused, the view gets bigger. But the layer is not upsized. Thus border is drawn in the middle of the view What am I doing wrong?

Mantas
  • 5,691
  • 6
  • 27
  • 24

1 Answers1

5

This seems to be a known issue with layer properties not getting transformed when being focused.

In the meantime, you can just provide a custom focus behavior by subclassing UITextField and implementing the focus behavior you would like. For example:

class TextField: UITextField  {
var borderLayer = CALayer()
override func awakeFromNib()
{
    super.awakeFromNib()
    self.borderLayer.borderColor = UIColor.blackColor().CGColor
    self.borderLayer.borderWidth = 2.0
    self.borderLayer.cornerRadius = 5.0
    self.borderLayer.frame = self.bounds
    self.layer.addSublayer(self.borderLayer)
}

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
    super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)
    if context.nextFocusedView === self
    {
        coordinator.addCoordinatedAnimations({
            self.borderLayer.bounds = self.expandedBounds()
        }){}
    }
    else if context.previouslyFocusedView === self
    {
        coordinator.addCoordinatedAnimations({
            self.borderLayer.frame = self.bounds
        }){}
    }
}

override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?)
{
    super.pressesBegan(presses, withEvent: event)
    self.borderLayer.bounds = self.bounds
}


override func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?)
{
    super.pressesEnded(presses, withEvent: event)
    self.borderLayer.bounds = self.expandedBounds()
}

func expandedBounds() -> CGRect
{
    let insetX:CGFloat = self.bounds.height * 0.3333
    let insetY:CGFloat = self.bounds.height * 0.075
    return CGRectInset(self.bounds, -insetX, -insetY)
}    } 

Here we've added a layer with border, and adjust it's bounds when focused or pressed. Kind of more work than it's worth in my opinion.

Community
  • 1
  • 1
beyowulf
  • 15,101
  • 2
  • 34
  • 40
  • Works well. Clearing and reseting the backgroundColor seems to be unnecessary though. Unless I'm missing some edge case. – Mantas Jul 25 '16 at 10:27
  • Scratch that. Doesn't seem to work after all. Well, it does work when moving from field to field. But if the field is triggered and keyboard opened - the default highlight shows up again.. – Mantas Jul 26 '16 at 15:14