Multiline multicolor attributed text in swift - swift

How can I build something like this using attributed text? I tried adding line feed (\n), it didn't work, just displayed first line and cropped next two, removing \n will display two parts in single line:
let mutableAttributedString = NSMutableAttributedString()
let regularAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 45.0), NSAttributedStringKey.foregroundColor: UIColor.yellow]
let boldAttribute = [NSAttributedStringKey.font: UIFont(name: "Avenir-Light", size: 25.0), NSAttributedStringKey.foregroundColor: UIColor.white]
let mutableAttributedString2 = NSMutableAttributedString()
let boldAttributedString = NSAttributedString(string: "person", attributes: boldAttribute)
let regularAttributedString = NSAttributedString(string: "\(self.requestCount)", attributes: regularAttribute)
mutableAttributedString2.append(boldAttributedString)
mutableAttributedString2.append(NSAttributedString(string: "\n"))
mutableAttributedString2.append(regularAttributedString)
self.btnStatsPeople.setAttributedTitle(mutableAttributedString2, for: .normal)

UILabel has one line by default.
This property controls the maximum number of lines to use in order to
fit the label’s text into its bounding rectangle. The default value
for this property is 1. To remove any maximum limit, and use as many
lines as needed, set the value of this property to 0.
UIButton creates default UILabel. So using 0 lines is a solution for your problem:
self.btnStatsPeople.titleLabel?.numberOfLines = 0

Related

How to add m² symbol at the end textField in swiftUI

how is it possible to add a m² at the end of the textfield?
For example, to add a € character at the end of a textfield, I was able to solve it with the numberFormatter.
textfield with euro sign
You have several options. The simplest solution is to use Unicode characters. Just use the superscripted version of the number 2 (U+00B2):
self.textField.text = "112 m\u{00B2}"
Alternatively you can use NSAttributedString or NSMutableAttributedString:
let defaultFont = UIFont.systemFont(ofSize: 15)
let superscriptedFont = UIFont.systemFont(ofSize: 10)
let text = NSMutableAttributedString(string: "112 m", attributes: [.font: defaultFont])
text.append(NSMutableAttributedString(string: "2", attributes: [.font: superscriptedFont, .baselineOffset: 5]))
self.textField.attributedText = text

Swift label not updating frame due change of font size

currently, I am creating a table view that contains an imageView as main UI item inside the cell and on top op that there is a label. Now I'm facing an issue where for long text, the frame of the label is not accurate, and for a long text it is taking a lot of space and it seems like there is a line break but there isn't, this is the issue:
Label issue
This are the properties of the label
Label properties
This is my ViewController and the constraints that I'm using
View Controller on Storyboard
Additional Details
For the Cell, I'm not adding extra code, I just have the IBOutlets and nothing more.
On the CellForRowAtIndexPath, I'm not doing additional code more than setting the image and setting the text.
Thanks
Try to change Content hugging Priority of Label
The font you've selected - Noto Nastaliq Urdu Bold - has very specific type layout properties.
Compare it with the default system font.
Using this code:
let fontDefault = UIFont.systemFont(ofSize: 17.0, weight: .bold)
guard let fontNotoBld = UIFont(name: "NotoNastaliqUrdu-Bold", size: 17) else {
fatalError("Could not create font!")
}
print("fontDefault.lineHeight:\t",fontDefault.lineHeight)
print("fontNotoBld.lineHeight:\t",fontNotoBld.lineHeight)
print()
print("fontDefault.ascender:\t",fontDefault.ascender)
print("fontNotoBld.ascender:\t",fontNotoBld.ascender)
print()
print("fontDefault.descender:\t",fontDefault.descender)
print("fontNotoBld.descender:\t",fontNotoBld.descender)
print()
print("fontDefault.xHeight:\t",fontDefault.xHeight)
print("fontNotoBld.xHeight:\t",fontNotoBld.xHeight)
print()
print("fontDefault.capHeight:\t",fontDefault.capHeight)
print("fontNotoBld.capHeight:\t",fontNotoBld.capHeight)
print()
we get this output in the debug console:
fontDefault.lineHeight: 20.287109375
fontNotoBld.lineHeight: 42.5
fontDefault.ascender: 16.1865234375
fontNotoBld.ascender: 32.368
fontDefault.descender: -4.1005859375
fontNotoBld.descender: -10.132000000000001
fontDefault.xHeight: 9.13916015625
fontNotoBld.xHeight: 9.112
fontDefault.capHeight: 11.97802734375
fontNotoBld.capHeight: 12.138000000000002
I don't know exactly why, but my assumption is that Noto Nastaliq Urdu supports many more language characters which often have very different shapes and heights.
You can either use a more standard font, or design your UI to accommodate the bigger spacing.
Edit
You could try using attributed text with line height settings. However, it will affect the top spacing of the text to a point that it may not suffice.
Here's an example with 3 labels:
top label uses default settings
second label changes maximumLineHeight to 17
third label changes maximumLineHeight to 26
let titleText = "Label with enough text to cause word wrapping onto multiple lines."
guard let fontNotoBold = UIFont(name: "NotoNastaliqUrdu-Bold", size: 17) else {
fatalError("Could not create font!")
}
// without paragraphStyle attribute
var attrString = NSMutableAttributedString(string: titleText)
attrString.addAttribute(NSAttributedString.Key.font, value: fontNotoBold, range:NSMakeRange(0, attrString.length))
label1.attributedText = attrString
// with paragraphStyle max line height: 17
let ps2 = NSMutableParagraphStyle()
ps2.maximumLineHeight = 17
attrString = NSMutableAttributedString(string: titleText)
attrString.addAttribute(NSAttributedString.Key.font, value: fontNotoBold, range:NSMakeRange(0, attrString.length))
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:ps2, range:NSMakeRange(0, attrString.length))
label2.attributedText = attrString
// with paragraphStyle max line height: 26
let ps3 = NSMutableParagraphStyle()
ps3.maximumLineHeight = 26
attrString = NSMutableAttributedString(string: titleText)
attrString.addAttribute(NSAttributedString.Key.font, value: fontNotoBold, range:NSMakeRange(0, attrString.length))
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:ps3, range:NSMakeRange(0, attrString.length))
label3.attributedText = attrString
Here's the result:
With a little more experimentation, such as adding a newline ("\n") at the beginning, you might be able to get it to a satisfactory appearance.

Attributed string cutting and displaying single word into two lines on UILabel

I'm creating attributed text using following attributes,
func attributedString(font: UIFont, contentColor: UIColor, alignment: NSTextAlignment) -> NSAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 0.6
paragraphStyle.lineHeightMultiple = 0.8
paragraphStyle.alignment = alignment
paragraphStyle.lineBreakMode = .byWordWrapping
let lineSpacingAttribute: [NSAttributedStringKey: Any] = [NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: contentColor]
let attributedString = NSAttributedString(string: self, attributes: lineSpacingAttribute)
return attributedString
}
I'm displaying this text on UILabel inside a custom tableViewCell. But, it is cutting a single word into two (cutting last letter of a word and displaying it on next line). I've set the numberOfLines to zero, and preferredMaxLayoutWidth for label. And I'm using a custom font.
This problem is happening on small screens only, iPhone SE and iPhone 5S simulators. But, on other simulators it is displaying correctly. Could you please help me to figure out what is wrong in this?
Thanks!
From Apple doc:
var preferredMaxLayoutWidth: CGFloat
This property affects the size of the label when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text flows to one or more new lines, increasing the height of the label.
Depending on your text you can use the adjustsFontSizeToFitWidth property with the minimumScaleFactor property

how to make text bold for detailedTextLabel in swift

cell!.textLabel?.text = vehicle["vrn"].string
cell?.detailTextLabel?.text = stateString
I want to display stateString as bold and also tried to use textLabel instead of detailedText but it did not work.
You can set the font property of the detailTextLabellike so:
cell.detailTextLabel?.font = UIFont.boldSystemFontOfSize(15.0)
You can use the font property inside the UILabel class.
// You need to set the name of your font here
cell.detailTextLabel?.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
There are other options using the attributedText
property but implies a little more of code, something like this:
// Define attributes to set
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 16)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create the attributed string
var attrString = NSAttributedString(string: "textOfYourLabel", attributes:attributes)
cell.detailTextLabel?.attributedText = attrString
I hope this help you.
If you want to bold text label using story board, simply select SHADOW colour in attributes inspector to same of that Text colour. Its works for me try it....

Swift UITextView with different formatting

Sorry for a basic question, but I'm not sure where to start. Is the following possible in Swift?
In a UITextView (Not a label, as in the possible duplicate), different bits of text having different formatting: for instance, a line of large text in the same UITextView as a line of small text. Here is a mockup of what I mean:
Is this possible in one UITextView?
You should have a look at NSAttributedString. Here's an example of how you could use it:
let largeTextString = "Here is some large, bold text"
let smallTextString = "Here is some smaller text"
let textString = "\n\(largeTextString)\n\n\(smallTextString)"
let attrText = NSMutableAttributedString(string: textString)
let largeFont = UIFont(name: "Arial-BoldMT", size: 50.0)!
let smallFont = UIFont(name: "Arial", size: 30.0)!
// Convert textString to NSString because attrText.addAttribute takes an NSRange.
let largeTextRange = (textString as NSString).range(of: largeTextString)
let smallTextRange = (textString as NSString).range(of: smallTextString)
attrText.addAttribute(NSFontAttributeName, value: largeFont, range: largeTextRange)
attrText.addAttribute(NSFontAttributeName, value: smallFont, range: smallTextRange)
textView.attributedText = attrText
The result: