Disable Line Wrapping in a multi-line UILabel - ios

Is there a way with a multi-line label (myLabel.numberOfLines = 0) to disable any kind of line wrapping so that if a line is too long to fit on one line of the label it just stops/kind of breaks off and doesnt wrap to the line below? So I can use "\n" to assign strings to other lines of the label. I know lines that are too long automatically wrap to the next line but I dont know if there is a no line wrap option.
So If I had a label with a line max of 10 chars per line
var firstLine : String = "This is 16 chars"
var secondLine : String = "This is too long"
myLabel.text = firstLine + secondLine
// It would look like this:
Output:
This is 16
This is to
As shown it just cuts off and doesnt wrap each line even though they dont fit

firstLine + secondLine will become 1 string This is 16 charsThis is too long, i dont think you can do something like described without code, you have to manually cut off the strings to 10 characters and add \n at the end, so it will become This is 16\nThis is to
Something like :
var string = message
let fontAttributes = [NSFontAttributeName: font]
var size = (string as NSString).sizeWithAttributes(fontAttributes)
while size.width > label.width {
string.removeAtIndex(string.endIndex.predecessor())
size = (string as NSString).sizeWithAttributes(fontAttributes)
}
string = string+"\n"

If you have desired length of your label, you can try this stupid but work method: To cut the string by yourself, use stringByPaddingToLength method.
Try below codes:
self.tempLabel.text = #"This is 16 chars fbaebfbefbefbeif";
self.tempLabel.text = [self.tempLabel.text stringByPaddingToLength:10 withString:#"" startingAtIndex:0];
See magic happens

Related

Get truncated text from UILabel in Swift [duplicate]

I have a single line UILabel. It has width = screen width and the content now is (the content of UILabel can change)
You have 30 seconds to make an impression during an interview
Currently, my UILabel is truncated tail and the word "duration" is not complete
self.nameLabel.lineBreakMode = NSLineBreakByTruncatingTail;
What I want is I want my UILabel still truncating tail and only display complete word.
Like the image below
Any help or suggestion would be great appreciated.
You can do something like this:
let labelWidth = CGRectGetWidth(label.bounds)
let str = "You will have 30 seconds till you give us a good impression" as NSString
let words = str.componentsSeparatedByString(" ")
var newStr = "" as NSString
for word in words{
let statement = "\(newStr) \(word) ..." as NSString
let size = statement.sizeWithAttributes([NSFontAttributeName:label.font])
if size.width < labelWidth {
newStr = "\(newStr) \(word)"
}
else{
break
}
}
newStr = newStr.stringByAppendingString(" ...")
self.label.text = newStr as String
Idea is: we split words and try check the width while appending from the beginning + the string "..." till we found the a word that will exceed the size, in the case we stop and use this new string
Ideally this is not possible,with default UILabel, when you set lineBreakMode to TruncatingTail, depending on the space required by the letter/word the OS will truncate it, one solution to fix the issue you can use following properties depending on your match.
Minimum Font Scale -- Use this property to specify the smallest multiplier for the current font size that yields an acceptable font size to use when displaying the label’s text. If you specify a value of 0 for this property, the current font size is used as the smallest font size.
Minimum Font Size -- When drawing text that might not fit within the bounding rectangle of the label, you can use this property to prevent the receiver from reducing the font size to the point where it is no longer legible.
i am not sure but try it:
nameLabel.adjustsFontSizeToFitWidth = NO;
nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
OR
If you are using storyboard follow these steps i tried this and it working fine
Open Attribute Inspector
Change Line Breaks to Truncate Tail then
Change AutoShrink to Minimum Font Size
here are my screenshots of label after and before applying these properties
new output

UILabel truncate tail and skip not complete word

I have a single line UILabel. It has width = screen width and the content now is (the content of UILabel can change)
You have 30 seconds to make an impression during an interview
Currently, my UILabel is truncated tail and the word "duration" is not complete
self.nameLabel.lineBreakMode = NSLineBreakByTruncatingTail;
What I want is I want my UILabel still truncating tail and only display complete word.
Like the image below
Any help or suggestion would be great appreciated.
You can do something like this:
let labelWidth = CGRectGetWidth(label.bounds)
let str = "You will have 30 seconds till you give us a good impression" as NSString
let words = str.componentsSeparatedByString(" ")
var newStr = "" as NSString
for word in words{
let statement = "\(newStr) \(word) ..." as NSString
let size = statement.sizeWithAttributes([NSFontAttributeName:label.font])
if size.width < labelWidth {
newStr = "\(newStr) \(word)"
}
else{
break
}
}
newStr = newStr.stringByAppendingString(" ...")
self.label.text = newStr as String
Idea is: we split words and try check the width while appending from the beginning + the string "..." till we found the a word that will exceed the size, in the case we stop and use this new string
Ideally this is not possible,with default UILabel, when you set lineBreakMode to TruncatingTail, depending on the space required by the letter/word the OS will truncate it, one solution to fix the issue you can use following properties depending on your match.
Minimum Font Scale -- Use this property to specify the smallest multiplier for the current font size that yields an acceptable font size to use when displaying the label’s text. If you specify a value of 0 for this property, the current font size is used as the smallest font size.
Minimum Font Size -- When drawing text that might not fit within the bounding rectangle of the label, you can use this property to prevent the receiver from reducing the font size to the point where it is no longer legible.
i am not sure but try it:
nameLabel.adjustsFontSizeToFitWidth = NO;
nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
OR
If you are using storyboard follow these steps i tried this and it working fine
Open Attribute Inspector
Change Line Breaks to Truncate Tail then
Change AutoShrink to Minimum Font Size
here are my screenshots of label after and before applying these properties
new output

UITextView attributed Alignment and size

First assume math is correct.
let textViewText = NSMutableAttributedString(string: "34\n+ 10\n+ 32344\n= 23424")
Im using a Textview to display input from the user. To make it easier to read I'm trying to get the text format like this
34
+ 10
+ 32344
= 23424
The other issue I'm having is with wrapping. Is there a way to resize each line to fit on its line?
34
= 23424
4356356
Is your text dynamic or static? If static, then all you need to do is to put the correct amount of spacing between your numbers and plus signs and then right justify the text.
self.textView.attributedText = NSMutableAttributedString(string: "34\n+ 10\n+ 32344\n= 23424")
self.textView.textAlignment = NSTextAlignment.Right
Result:
You can accomplish this by using a right-aligned tab stop in your paragraph style, and separating your operators and values with a tab.
let string = "\t34\n+\t10\n+\t32344\n=\t23424"
let paragraph = NSMutableParagraphStyle()
paragraph.tabStops = [NSTextTab(textAlignment: .Right, location: 200, options: [:])]
let attributedString = NSAttributedString(string: string, attributes:[NSParagraphStyleAttributeName: paragraph])

Swift - Placeholder long text - cut the middle

I have UITextField with long placeholder like this:
"QWERTYUIOPASDFGHJKLZXCVBNM", but my textfield is small and when I use function textField.adjustsFontSizeToFitWidth = true the minimumFontSize that I can set is 9 but still I can't fit the text into the textField. I want to cut the middle of the text and I expect the text to be "QWERTY...CVBNM" how to do that?
func cutTheMiddleOfLongString(var string:String) -> String {
if(countElements(string)>20){
let begining = string[advance(string.startIndex, 0)..<advance(advance(string.startIndex, 0), 12)]
let ending = string[advance(string.startIndex, countElements(string)-8)..<advance(advance(string.startIndex, countElements(string)-8), 8)]
string = begining + "..." + ending
}
return string
}
This will take first 12 letters and last 8 letters of the string and will put ... between them(begining ending).

UILabel lineBreakMode, break at specific character

Is there a way to break the text in a UILabel at a specific character say ";" ??
I don't want it to be broken with Word Wrap or character Wrap.
Sure, just replace all the occurrences of ";" with ";\n" before you show the string.
There is another way which will work in limited circumstances. You can replace your normal spaces (\U+0020) with non-breaking spaces (\U+00A0). This will allow you to limit the number of places your string breaks. For example if you had a string like;
I have a string with two sentences. I want it to preserve the sentences.
By carefully using non-breaking spaces you can get it to break like this;
I have a string with two sentences.
I want it to preserve the sentences.
HOW:
For Strings in InterfaceBuilder:
Go to System Preferences -> Keyboard -> Input Sources -> +
Select the category 'Others' and the keyboard 'Unicode Hex Input'
Select 'Add'
Make sure 'Show Input method in menu bar' is selected.
CLose System Preferences
Go back to XCode and find your string
Using the keyboard menu in your menu bar, select the Unicode keyboard
In your string select a space. Type Option+00a0. A space will appear when you've completed the 4 digit sequence. That space is a non-breaking space. Repeat for all spaces you need to.
For programmatic strings you can just add \U00A0 as appropriate.
You can use (\r) instead of newline (\n) to create a line break.
Set numberOfLines to 0 to allow for any number of lines.
yourLabel.numberOfLines = 0;
Like With in your case just replace ; with ;\n
NSString *string = #"This; is a; NSString";
string = [string stringByReplacingOccurrencesOfString:#";"
withString:#";\n"];
You can't break line using ; this character. if you want to break line then replace this character with \n character.
label.text=[label.text stringByReplacingOccurrencesOfString:#";" withString:#"\n"];
And make
label.numberOfLines = 0.
And Update the label frame
CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:label.lineBreakMode];
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, labelSize.height);
You can do with combination of newline character and line break.Check the following code,
self.testLabel.text = #"abc;\nabc;";
self.testLabel.numberOfLines = 0;
CGSize labelSize = [self.testLabel.text sizeWithFont:self.testLabel.font
constrainedToSize:self.testLabel.frame.size
lineBreakMode:self.testLabel.lineBreakMode];
self.testLabel.frame = CGRectMake(
self.testLabel.frame.origin.x, self.testLabel.frame.origin.y,
labelSize.width, labelSize.height);

Resources