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
}
}
Related
Currently, my text within a UITextField is truncating at the tail (eg. "Hello, Wor..."). I want the to truncate the text from the leading edge (eg. "...lo, World!").
I believe using NSMutableParagraphStyle's lineBreakMode with NSMutableAttributedString might work
let longString = "Hello World"
// Just for demo purposes, you can use auto layout etc
let textfield = UITextField(frame: CGRect(x: 40, y: 200, width: 30, height: 100))
textfield.layer.borderWidth = 2
textfield.layer.borderColor = UIColor.gray.cgColor
// Use a paragraph style to define the truncation method
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingHead
// Create an attributed string and apply the paragraph style
let attributedString = NSMutableAttributedString(string: longString)
attributedString.addAttribute(.paragraphStyle,
value: paragraphStyle,
range:NSMakeRange(0, attributedString.length))
// Set the text field's attributed text as the attributed string
textfield.attributedText = attributedString
This gives something like this, which is what I think you want:
You just have to update the text attributes (e.g., defaultTextAttributes) with a .paragraphStyle with a lineBreakMode of .byTruncatingHead.
I would not just replace the .paragraphStyle, though. I would fetch it, update its lineBreakMode, and then update the text attributes with that:
let oldStyle = textField.defaultTextAttributes[.paragraphStyle, default: NSParagraphStyle()] as! NSParagraphStyle
let style = oldStyle.mutableCopy() as! NSMutableParagraphStyle
style.lineBreakMode = .byTruncatingHead
textField.defaultTextAttributes[.paragraphStyle] = style
Here it is with .byTruncatingHead, .byTruncatingMiddle and .byTruncatingTail, respectively:
I have a label that uses a NSMutableAttributedString to write out the text as:
What I want to do is lower the asterisk's top padding so that it's midY is even with the word Cuisine like below:
How can I add padding using a NSMutableAttributedString?
I know I can create a separate label with the asterisk alone and use anchors w/ a constant to center it but I want to see how this is possible using a NSMutableAttributedString
let cuisineLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
let attributedText = NSMutableAttributedString(string: "Cuisine ", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17), NSAttributedStringKey.foregroundColor: UIColor.lightGray])
attributedText.append(NSAttributedString(string: "*", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24), NSAttributedStringKey.foregroundColor: UIColor.red]))
label.attributedText = attributedText
return label
}()
The baselineOffset attribute key is used for this purpose.
let cuisine = NSMutableAttributedString(string: "Cuisine")
let asterisk = NSAttributedString(string: "*", attributes: [.baselineOffset: -3])
cuisine.append(asterisk)
Obviously, you will have to calculate the offset using the font size of the rest of the text. This is why I believe that using a full width asterisk (*) is easier.
Result with full width asterisk (you might want its font size to be a proportion of the font size of the rest of the string):
As Code Different points out, you can do this with baselineOffset attribute. A value of -8 should work for your case:
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
self.view = view
let cuisineLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
let attributedText = NSMutableAttributedString(string: "Cuisine ", attributes: [
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17),
NSAttributedStringKey.foregroundColor: UIColor.lightGray])
attributedText.append(NSAttributedString(string: "*", attributes: [
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 24),
NSAttributedStringKey.baselineOffset: -8,
NSAttributedStringKey.foregroundColor: UIColor.red]))
label.attributedText = attributedText
return label
}()
view.addSubview(cuisineLabel)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
If you're struggling with line height offsets being messed up because of the new baseline and you're using a multi-line label, try playing with lineHeightMultiple:
let lineStyle = NSParagraphStyle()
lineStyle.lineHeightMultiple = 0.8
...
NSAttributedStringKey.paragraphStyle = style
If not (and you're using multiple labels stacked on top of one another) then you probably just need to adjust the frame of each label in the series to compensate.
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.
So basically, I have created a speedometer but right now I have it outputting "30km/h" on one line.
What I want it to look like is have 30 on one line and km/h below it.
And if anyone knows how to make that thicker line that goes up the faster you go, that would be a great help.
Here is what my code looks like right now:
let speed = (location.speed*3.6)
let speedInt: Int = Int(speed)
//statusLabel.backgroundColor = UIColor.red
//statusLabel.layer.cornerRadius = 10.0
//statusLabel.clipsToBounds = true
let statusLabel = UILabel()
let size:CGFloat = 70.0
statusLabel.textColor = UIColor.black
statusLabel.textAlignment = .center
statusLabel.font = UIFont.systemFont(ofSize: 13.0)
statusLabel.frame = CGRect(x : 172.0,y : 580.0,width : size, height : size)
statusLabel.layer.cornerRadius = size / 2
statusLabel.layer.borderWidth = 2.0
statusLabel.layer.backgroundColor = UIColor.white.cgColor
statusLabel.layer.borderColor = UIColor.init(colorLiteralRed: 14.0/255, green: 122.0/255, blue: 254.0/255, alpha: 1.0).cgColor
statusLabel.text = "\(speedInt) km/h"
You should use UILabel's attributedText property in order to achieve this look.
Use \n to insert a new line to the label.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let bigAttr = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont.systemFont(ofSize: 60, weight: UIFontWeightLight),
NSParagraphStyleAttributeName: paragraphStyle]
let smallAttr = [NSFontAttributeName: UIFont.systemFont(ofSize: 12, weight: UIFontWeightLight)]
let attributedString = NSMutableAttributedString(string: "\(speedInt)", attributes: bigAttr)
attributedString.append(NSAttributedString(string: "\nkm/h", attributes: smallAttr))
statusLabel.attributedText = attributedString
Add a \n where you want to split the string. "30 \n kmh"
Or simply add two labels.
You can simply add 2 lines in label with the help of UI. Just take a look at below snap
as shown above you can set the line break by word wrapping and simply add the title whole you want. in your case 0 km/h.
Then put the cursor at k and press ctrl + Enter. The title will appears in two lines.
I have a UILabel that is put as titleView in the navigation bar. I want it to have 2 lines, where the first line can be truncated and the second is center aligned.
In code it looks more less like this:
let label = UILabel()
let text = NSAttributedString(string: "Long long long text\nsecond line")
label.attributedText = text
label.textAlignment = .Center
label.numberOfLines = 0
label.lineBreakMode = .ByTruncatingTail
label.sizeToFit()
self.navigationItem.titleView = label
The effect in case of the first line text is not exceeding available
space is like this:
It's pretty good, but when the first line text is longer than:
let text = NSAttributedString(string: "Very very very very very long text\nsecond line")
I want to achieve like below.
How it can be done? I experimented with numberOfLines and lineBreakMode but it's not worked.
change your line breakmode to ByTruncatingMiddle instead of ByTruncatingTail. Something like below,
label.lineBreakMode = .ByTruncatingMiddle
Hope this will help :)
Navigation Tittle with sub-Tittle (Multiline Navigation Tittle)
Use NSMutableAttributedString with UITextView instead of UILabel
(because, if tittle is large then UILabel lineBreakMode with .byTruncatingTail is not working for first line in UILabel)
func multilineNavigation(title:String,subTitle:String) {
DispatchQueue.main.async {
let titleAttributedStr = NSMutableAttributedString(string: title, attributes: [NSAttributedStringKey.foregroundColor: UIColor.orange,NSAttributedStringKey.font: UIFont(name: "Helvetica Neue", size: 17.0) ?? UIFont()])
let subTitleAttributedStr = NSMutableAttributedString(string: "\n\(subTitle)", attributes: [NSAttributedStringKey.foregroundColor: UIColor.green,NSAttributedStringKey.font: UIFont(name: "Helvetica Neue", size: 12.0) ?? UIFont()])
titleAttributedStr.append(subTitleAttributedStr)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1
paragraphStyle.lineBreakMode = .byTruncatingTail
titleAttributedStr.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, titleAttributedStr.length))
let textView = UITextView()
textView.attributedText = titleAttributedStr
textView.backgroundColor = .clear
textView.isUserInteractionEnabled = false
textView.textContainerInset = .zero
textView.textAlignment = .center
textView.frame = CGRect(x: 0, y: 0, width: textView.intrinsicContentSize.width, height: 44)
self.navigationItem.titleView = textView
}
}