[iOS] Float Input View

Roy Ng @ Redso
iOS App Development
2 min readMay 10, 2017

Float Labels for Edit Text was introduced in Android’s Material Design.
It’s aimed to solve the problem that the hint text / placeholder is hidden due to the user inputting text.

Example of Float Labels at Android

There is already existing very famous library named JVFloatLabeledTextField which implement the “Float Label Pattern” for iOS.

Yes. It’s good enough for most of the cases. Except the animation is not smooth enough for me. Why? Because the animation is just the combination of two separate animations.
1) Fade out of the original place holder.
2) Fade in and slide up of floated place holder with desired text color.

Therefore, I am writing my own float input to achieve this animation:
- The original place holder should float up, scale down and text color is changed gradually.

Just like this: Youtube Video Demo

To achieve this smooth animation, we must use CoreText.
According to the document of CATextLayer, we can animate the fontSize and foregroundColor. To animate it is easy, just use CATransaction.

CATransaction.begin()    CATransaction.setAnimationDuration(animationDuration)    CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut))    
placeHolderLabel.foregroundColor = floatPlaceHolderColor.cgColor placeHolderLabel.fontSize = floatPlaceHolderFontSize
layout()
CATransaction.commit()

The library is compatible with Interface Builder. It’s reduce the amount of codes to configure for each instance.
For string localisation, we can set a global string transformer:

RSFloatInputView.stringTransformer = {
orginal in
// Transform the place holder string configured in XIB with your own way.
// e.g return NSLocalizedString(orginal, comment: orginal)
return orginal.replacingOccurrences(of: "TXT_", with: "")
}

In this way, all strings configured in IB will be transformed according the block above. For example, TXT_Hello will be transformed to Hello.

Similarly, usually for one project we define only one or two styles for the same widget. We can set the properties in IB but not quite efficiency when we heavily reuse the widget. Therefore, instance transformer is introduced. We can set the style using Tag of the view and apply the style when the instance is created.

RSFloatInputView.instanceTransformer = {
instance in
// Support multi-styles in one place using the tag
if instance.tag == 0 {
instance.floatPlaceHolderColor = UIColor.brown
instance.textColor = UIColor.darkText
instance.tintColor = UIColor.brown
}
if instance.tag == 1 {
instance.floatPlaceHolderColor = UIColor.blue
instance.textColor = UIColor.darkText
instance.tintColor = UIColor.blue
}
}

It’s always easy to use library. But you will learn a lot by writing your own one.

--

--

Roy Ng @ Redso
iOS App Development

Redso: Expert in building iPhone apps, Android apps, Mobile Web, scalable backend on Cloud Platforms, and integrating them all together.