UITextField text color transparent - ios

I want to set the color of my text in my UITextField. The textborder is black but the color on the inside is transparent. How do I add color to it?
Here is what I have:
let memeTextAttributes:[String:Any] = [
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: 3.0]
topText.delegate = self
topText.defaultTextAttributes = memeTextAttributes
topText.text = "TOP"
topText.textAlignment = NSTextAlignment.center
topText.adjustsFontSizeToFitWidth = true
topText.center.x = self.view.center.x
topText.center.y = self.view.frame.origin.y + 150
topText.minimumFontSize = 10
topText.textColor = UIColor.white

I had to do an insane amount of research. Here is what i ended up with:
let memeTextAttributes:[String:Any] = [
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: -5.0
]
NSStrokeWidthAttributeName had to be a NEGATIVE number/float to fill in the color, not a POSITIVE number/float! A positive float made the color transparent.
My project - https://github.com/ryanwaite28/ios-developer/blob/master/Meme%20Me/MemeMe2/MemeCreateEditController.swift
Took me the whole day.
Wowzerz...

Sorry I misunderstood what you wanted. If you want the background to be transparent, the text border color to be black, and the text color to be white, you should 1) set the text field's backgroundColor property to .clear, 2) set the borderColor property of the text field's layer property to be UIColor.black.cgColor, 3) set the borderWidth property of the text field's layer property to be 1, and 4) set the text field's textColor property to .white.
topText.backgroundColor = .clear
topText.layer.borderColor = UIColor.black.cgColor
topText.layer.borderWidth = 1
topText.textColor = .white

Related

How to make a label's text look good on top of an image?

I have a UIButton, on which I set a UIImage (by using set(_:for:) method). After that, I add a label on it with some text (It should be white). The problem is: When I use some photos, which have bright colours (close to white), it's hard to see some characters of the text. Here how it looks like (the button isn't very big, hence the quality of the image is low, too):
I've tried to add a UIView between the button and the label and to manipulate its alpha, but that doesn't help. If you know how the problem can be solved (without changing text's colour), I would appreciate your help.
The most common approach is to set the label's background color to a partially transparent black color. Then maybe round the labels corners for a nice look.
let label = ... // your label
label.backgroundColor = UIColor(white: 0.0, alpha: 0.4) // adjust alpha as desired
label.layer.cornerRadius = 4 // adjust as desired
Another option, instead of adding a background to the label, is to use attribute text for the label and give the white text a black outline.
let attrs: [NSAttributedStringKey: Any] = [
.foregroundColor: UIColor.white,
.strokeColor: UIColor.black,
.strokeWidth: -2.0,
.font: UIFont.systemFont(ofSize: 20) // Use whatever font you want
]
let attrStr = NSAttributedString(string: "Grand Royal", attributes: attrs)
label.attributedText = attrStr
Yet another option is to setup the label with a shadow:
let label = ... // your label
label.shadowColor = .black
label.shadowSize = CGSize(width: 1, height: 1)
The shadow can be created using attribute text and this gives you more control:
let shadow = NSShadow()
shadow.shadowColor = UIColor.black
shadow.shadowOffset = CGSize(width: 0, height: 0)
shadow.shadowBlurRadius = 3
let attrs: [NSAttributedStringKey: Any] = [
.foregroundColor: UIColor.white,
.shadow: shadow,
.font: UIFont.systemFont(ofSize: 40)
]
let attrStr = NSAttributedString(string: "Grand Royal", attributes: attrs)
label.attributedText = attrStr
This puts a halo around the text. Adjust the shadow properties to suit your needs.

How to color potion of an UILabel in swift 3

I want to achieve something like this without using 2 labels.
How can I create an UILabel like this.Please help me.
You can use the NSBackgroundColorAttributeName property of the NSMutableAttributedString to achieve the above result
var attributedString = NSMutableAttributedString(string:yourString)attributedString.addAttribute(NSBackgroundColorAttributeName, value: .redColor() , range: range)
yourLabel.attributedText = attributedString
For achieving this output we use NSAttribute class
Try below code
//This is for setting border of UILabel
let labelColor = UIColor(colorLiteralRed: 255.0/255.0, green: 115.0/255.0, blue: 116.0/255.0, alpha: 1.0)
lblNoOfDays.layer.masksToBounds = true
lblNoOfDays.layer.borderWidth = 1.0
lblNoOfDays.layer.borderColor = labelColor.cgColor
//This is value we display
let strValueTitle = "No of Days"
let strValue = "04"
//Attribute dictionary we use
//NSFontAttributeName:- sets font and it's size
//NSForegroundColorAttributeName:- sets text colour
//NSBackgroundColorAttributeName:- sets background color
let attributeTitle = [NSFontAttributeName: UIFont.systemFont(ofSize: 11.0), NSForegroundColorAttributeName: labelColor, NSBackgroundColorAttributeName: UIColor.clear]
let attributeVal = [NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName: UIColor.white, NSBackgroundColorAttributeName: labelColor]
//Implement attributes to string
let attributTitleString = NSMutableAttributedString(string: strValueTitle, attributes: attributeTitle)
let attributeValue = NSAttributedString(string: strValue, attributes: attributeVal)
//Append attributed string
attributTitleString.append(attributeValue)
//Assign attributed string to label
lblNoOfDays.attributedText = attributTitleString
lblNoOfDays.sizeToFit()
You need to set padding in UILabel for getting desired output.

Underline covers text in NSAttributedString

I'm trying to create an attributed string but the underline covers my text instead of appearing behind it:
Is there a way to fix this? I'm using the following code:
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 10.0
let attributes = [NSForegroundColorAttributeName: UIColor.white,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleThick.rawValue,
NSUnderlineColorAttributeName: UIColor.red,
NSParagraphStyleAttributeName: paragraphStyle]
let attributedString = NSAttributedString(string: "Story", attributes: attributes)
Thanks!
EDIT:
To give more context:
I'm displaying the attributed string on a UILabel placed in a .xib file:
view.textLabel.attributedText = attributedString
The label has the following font:
System Bold 32.0
I'm running the code on iPhone 6 - iOS 10.3 simulator.
EDIT 2:
I should have mentioned that the label may, at some point, contain more than one line of text. That's why the numberOfLines is set to 0.
EDIT 3:
If anybody encounters this problem -- it seems that there is a lot of difference in how underline is drawn on iOS 9 vs 10 as well as UILabel vs UITextView. I've ended up having to draw the underline myself by subclassing NSLayoutManager.
Yes, there is such problem as you have described. It shows up when you use multiline UILabel, so not only setting numberOfLines to 0, but type more than 1 line in it.
Example
let selectedStringAttributes: [String: Any]
= [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 28),
NSForegroundColorAttributeName: UIColor.green,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue,
NSUnderlineColorAttributeName: UIColor.green]
let label = UILabel(frame: CGRect(x: 100, y: 100, width: 500, height: 100))
label.numberOfLines = 0
label.attributedText = NSAttributedString(string: "String to test underline", attributes: selectedStringAttributes)
And everything will look pretty good.
But if you want to use such text:
label.attributedText = NSAttributedString(string: "String to\ntest underline", attributes: selectedStringAttributes)
or label's width is too short, than:
So the reason for such behaviour is of course bug in NSAttributedString. As it mentioned in radar there is a workaround
You should add this attribute to your NSAttributedString
NSBaselineOffsetAttributeName: 0
And magic will happen.
Instead of using NSAttributedString you can draw border below the label with x space using this.
let space:CGFloat = 10
let border = CALayer()
border.backgroundColor = UIColor.red.cgColor
border.frame = CGRect(x: 0, y: (label?.frame.size.height)! + space, width: (label?.frame.size.width)!, height: 1)
label?.layer.addSublayer(border)
On my machine, showing your attributed string in a black-backgrounded UILabel, it makes a quite nice-looking display:
The red thick underline is nicely separated from the text, and is interrupted to allow the descender of the "y" to pass through it.
NOTE You cannot combine the font of the UILabel (set in Interface Builder) with its attributedText. You must set the entire label's text formatting in the attributedText. So, my code looks like this:
let attributes : [String:Any] = [NSForegroundColorAttributeName: UIColor.white,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleThick.rawValue,
NSUnderlineColorAttributeName: UIColor.red,
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 32)]
let attributedString = NSAttributedString(string: "Story", attributes: attributes)
lab.backgroundColor = .black
lab.attributedText = attributedString
(You will notice that I removed your stipulation of the paragraph line spacing; there is only one line, so this stipulation adds nothing. However, I get the same result even if I restore it.)
So this is my solution to this issue.
I think it is "cleaner" and easier.
Post me if you dont understand :)
class BottomLineTextField: UITextField {
var bottomBorder = UIView()
override func awakeFromNib() {
super.awakeFromNib()
setBottomBorder()
}
func setBottomBorder() {
self.translatesAutoresizingMaskIntoConstraints = false
bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
hasError = false
bottomBorder.translatesAutoresizingMaskIntoConstraints = false
addSubview(bottomBorder)
bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set underline height
}
}

How to change the font and text color of the title of UINavigationBar

I want to be change the font of the title to Avenir, and I want to make it white. Here is my code in the viewDidLoad method:
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Avenir", size: 20)!]
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
This code only changes the color of the title, not the font. Additionally, I tried implementing this in the App Delegate File, but that did not work.
Here is what my UINavigationBar looks like:
I want the title to have a font of Avenir as well. How do I achieve this?
It seems this is needed as well:
self.navigationController?.navigationBar.barStyle = UIBarStyle.Black // I then set the color using:
self.navigationController?.navigationBar.barTintColor = UIColor(red: 204/255, green: 47/255, blue: 40/255, alpha: 1.0) // a lovely red
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() // for titles, buttons, etc.
let navigationTitleFont = UIFont(name: "Avenir", size: 20)!
self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: navigationTitleFont]
If you want the styles to be applied through out the whole app add these lines in the AppDelegate.m file.
NSShadow* shadow = [NSShadow new];
shadow.shadowOffset = CGSizeMake(0.0f, 0.0f);
shadow.shadowColor = [UIColor blackColor];
[[UINavigationBar appearance] setTitleTextAttributes: #{
NSForegroundColorAttributeName: [UIColor whiteColor],
NSFontAttributeName: [UIFont fontWithName:#"Kelvetica Nobis" size:20.0f],
NSShadowAttributeName: shadow
}];
NSForegroundColorAttributeName sets the Font color.
NSFontAttributeName sets a custom font face to the title text.
NSShadowAttributeName applies a nice shadow effect to the text, you can remove this part if you want.
Also in advance, you can add these line to hide the text that comes up in back button in action bar when you navigate to another view within the navigation controller.
[[UIBarButtonItem appearance]
setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000)
forBarMetrics:UIBarMetricsDefault];
Hope this help your question :)
In case someone needs this in Swift 4:
let navBarAppearance = UINavigationBar.appearance()
navBarAppearance.barTintColor = .red
navBarAppearance.tintColor = .white
navBarAppearance.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "Avenir", size: 20)!]
Your code is OK you just need to set all of titleTextAttributes in one line:
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white , NSFontAttributeName: UIFont(name: "Avenir", size: 17)!]
In Swift 5:
let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "Avenir", size: 20)!]
appearance.largeTitleTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "Avenir", size: 35)!]
Code here are for Title and Large title. you can also remove custom font if you want system font.
I'm updating this for iOS 15. If you have a scroll view that pushes something behind the Nav Bar it WILL change the NavigationBar background if you do NOT set "navigationBar.scrollEdgeAppearance".
So here is a simple config to set it for ALL of your views in ViewDidLoad of your main ViewController.
// Set top Nav Bar behavior for ALL of app
let standardAppearance = UINavigationBarAppearance()
// Title font color
standardAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
// prevent Nav Bar color change on scroll view push behind NavBar
standardAppearance.configureWithOpaqueBackground()
standardAppearance.backgroundColor = UIColor.blue
self.navigationController?.navigationBar.standardAppearance = standardAppearance
self.navigationController?.navigationBar.scrollEdgeAppearance = standardAppearance
So the 'scrollEdgeAppearance' you can set title color, tint, NavBar color and the works. The standardAppearance is what shows at loading.
Took me a while to figure this one out for iOS15.
You're welcome! :-)
I would just create an outlet and do this:
#IBOutlet weak var navigationBar: UINavigationBar!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Avenir", size: 30)!]
}

NSForegroundAttributeName not working. Text fill renders transparent

I am trying to make the fill for this text white, but the fill is transparent, and when I change the NSForegroundAttribureName, it has no effect below is my code.
let textAttributes = [
NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName : 3.0,
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSStrokeColorAttributeName : UIColor.blackColor()
]
In viewDidLoad()
textFieldTop.defaultTextAttributes = textAttributes
How do I make the fill for the font white?
let textAttributes = [
NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName : -3.0,//Shpuld be in minus
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSStrokeColorAttributeName : UIColor.blackColor()
]
Text becomes invisible when stroke is added
kCTStrokeWidthAttributeName. This attribute, interpreted as a percentage of font point size, controls the text drawing mode: positive values effect drawing with stroke only; negative values are for stroke and fill.

Resources