Reputation: 1
I have a button with some text and i need to add border to this is text 0.2 px, i used @IBDesignable but it work for button not for text.
my code:
@IBInspectable var borderWidth: CGFloat = 1.0{
didSet{
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderTextColor:UIColor?{
didSet{
layer.borderColor = borderTextColor?.cgColor
}
}
Upvotes: 0
Views: 2354
Reputation: 391
If you want to add a border to the text itself you can use an attributed string to add a stroke to the text. You can do this for most text related UI elements within UIKit
such as a UILabel
or UIButton
// Create the stroke attributes
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.strokeWidth: -4.0
];
// Create the text with a stroke as an attributed string
let textWithStroke = NSAttributedString(
string: "Button Text",
attributes: attributes
);
// Set the attributed string to the button
button.setAttributedTitle(textWithStroke, for: .normal);
Use a negative value for the .strokeWidth
so the stroke outlines the outside of the text and not the inside
If you want to edit the font just add the NSAttributedString.Key.font
key with a value of UIFont
to the attributes
array
Upvotes: 2
Reputation: 116
You are adding border to your UIButton
not UILabel
. Use UILabel
for text not UIButton
text and then assign border to UILabel
like this
yourLabel.layer.borderColor = UIColor.black.cgColor
yourLabel.layer.borderWidth = 2
yourLabel.layer.cornerRadius = 5
Upvotes: 0
Reputation: 26
You can simply give the button a ID & just use normal CSS Like this-
#myButton{text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;}
This will just create a shadow like outline to your text. Manage the colors according to your needs.
Upvotes: -1