I'd like to set border color using storyboard if possible. I've seen answer here: UITextField border color
And I followed answer in storyboard:
All properties set, but TextField doesn't show border. Any suggestions?
borderColor needs a value with type CGColor . But only UIColor types can be set via Interface Builder's User Defined Runtime Attributes! So, you must set a UIColor to a proxy property via Interface Builder, then intercept that call to set the equivalent CGColor to the layer. borderColor property.
You can change the TextField border color globally by defining the inputDecorationTheme and then adding the OutlineInputBorder widget. Inside the OutlineInputBorder widget, you can specify which type of border you want to change. for example, enabledBorder , focusedBorder , and so on, and then assign the color.
An object that displays an editable text area in your interface.
Well as Bogdan pointed out, you could very well do that with simple subclassing and just a few bits of code. After that everything will be editable in Storyboards.
Code for illustration (Swift 3.1):
@IBDesignable
class FormTextField: UITextField {
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
}
Edit: You'll see this in your Attributes Inspector
As Bogdan pointed out it's true that you can't find the layer.borderColor property in storyboard as it's a run time thing.
However still you can set the borderColor without using IB_DESIGNABLE, on any view(or UIView Subclass) with a little bit of coding.
Below are the steps how to achieve it,
P.S: Remember, Categories can't have stored properties. 'borderUIColor' is used as a calculated property, just as a reference to achieve what we're focusing on.
Please have a look at the below code sample;
Objective C:
Interface File:
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
@interface CALayer (BorderProperties)
// This assigns a CGColor to borderColor.
@property (nonatomic, assign) UIColor* borderUIColor;
@end
Implementation File:
#import "CALayer+BorderProperties.h"
@implementation CALayer (BorderProperties)
- (void)setBorderUIColor:(UIColor *)color {
self.borderColor = color.CGColor;
}
- (UIColor *)borderUIColor {
return [UIColor colorWithCGColor:self.borderColor];
}
@end
Swift 3.1:
extension CALayer {
var borderUIColor: UIColor {
set {
self.borderColor = newValue.cgColor
}
get {
return UIColor(cgColor: self.borderColor!)
}
}
}
And finally go to your storyboard/XIB, follow the remaining steps;
Edit: You've to set layer.borderWidth property value to at least 1 to see the border color.
Build and Run. Happy Coding. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With