determine the maximum number of characters a UILabel can take
Well, what I did here works though there may be another, more efficient (yet less straight-forward) way.
What I did was just calculate the size of the rect needed for the text, see if it fits in the label's frame, and if not, chop off a character and try again.
@interface LTViewController ()
@property (nonatomic, weak) IBOutlet UILabel *label1;
@property (nonatomic, weak) IBOutlet UILabel *label2;
@end
@implementation LTViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label1 = self.label1;
UILabel *label2 = self.label2;
UIFont *font = label1.font;
NSString *text = @"This is some text that will go into labels 1 and 2.";
CGRect label1Frame = label1.frame;
NSUInteger numberOfCharsInLabel1 = NSNotFound;
for (int i = [text length]; i >= 0; i--) {
NSString *substring = [text substringToIndex:i];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:substring
attributes:@{ NSFontAttributeName : font }];
CGSize size = CGSizeMake(label1Frame.size.width, CGFLOAT_MAX);
CGRect textFrame = [attributedText boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
if (CGRectGetHeight(textFrame) <= CGRectGetHeight(label1Frame)) {
numberOfCharsInLabel1 = i;
break;
}
}
if (numberOfCharsInLabel1 == NSNotFound) {
// TODO: Handle this case.
}
label1.text = [text substringToIndex:numberOfCharsInLabel1];
label2.text = [text substringWithRange:NSMakeRange(numberOfCharsInLabel1, [text length] - numberOfCharsInLabel1)];
}
@end
This yields:
It's up to you to handle the error conditions. For example, the rest doesn't completely fit into label2 and it's probably going to chop in the middle of a word more often then not.
How do you limit UILabel characters in swift?
If you want to limit the UILabel to just 10 characters then
you just have to assign it with a text with length of 10.
You can use NSString
and NSRange
to extract the text you need.
let str = "This is a Very Long Label"
let nsString = str as NSString
if nsString.length >= 10
{
label.text = nsString.substringWithRange(NSRange(location: 0, length: nsString.length > 10 ? 10 : nsString.length))
}
How to limit UILabel to 25 characters and show dots if exceeds using auto layout
You can do something like,
if (lbl.text?.characters.count)! >= 25 {
let index = lbl.text?.index((lbl.text?.startIndex)!, offsetBy: 25)
lbl.text = lbl.text?.substring(to: index!)
lbl.text = lbl.text?.appending("...")
}
//lbl.adjustsFontSizeToFitWidth = true
//lbl.lineBreakMode = .byTruncatingTail
And your constraints
should be like : Top,leading,fixed height
!
How To Count how many characters can come in a UILabel line?
Try this :
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{CGSize size;
if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
// code here for iOS 5.0,6.0 and so on
CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17]];
size = fontSize;
}
else {
// code here for iOS 7.0
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica Neue" size:19], NSFontAttributeName,
nil];
CGRect fontSizeFor7 = [text boundingRectWithSize:CGSizeMake(571, 500)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
size = fontSizeFor7.size;
}return size.height +30 ;
}
Get number of characters in one line of UILabel
Maybe you could approach the problem in a different way. You can decide how many characters you allow in one label.
let limitLength = whatever length you want to allow
func textField(username: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = username.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= limitLength
}
How to set maximum length for UILabel?
Based on your comment, what you actually implemented would work. You just have to ensure your syntax is correct.
Assuming your getting a string from a database:
NSString *string = stringFromDatabase;
//execute your conditional if statement
if (string.length > 50) { //meaning 51+
/* trim the string. Its important to note that substringToIndex returns a
new string containing the characters of the receiver up to, but not
including, the one at a given index. In other words, it goes up to 50,
but not 50, so that means we have to do desired number + 1.
Additionally, this method includes counting white-spaces */
string = [string substringToIndex:51];
}
Then we must set the labels text, this doesn't happen autonomously. So completely:
NSString *string = stringFromDatabase;
if (string.length > 50) {
string = [string substringToIndex:51];
}
self.someUILabel.text = string;
I think the way you are doing it is probably not user friendly. You're getting the string of a UILabel
that already has text set and then resetting it. Instead, you should set the desired text to the UILabel
before it is called by the delegate
How to limit UILabel's max characters
You can iterate your string indices counting the characters, if it is a chinese character add 2 otherwise add 1. If the count is equal to 16 return the substring up to the current index with "…" at the end. Something like:
extension Character {
var isChinese: Bool {
String(self).range(of: "\\p{Han}", options: .regularExpression) != nil
}
}
extension StringProtocol {
var limitedLenghtLabelText: String {
var count = 0
for index in indices {
count += self[index].isChinese ? 2 : 1
if count == 16 {
let upperBound = self.index(after: index)
return String(self[..<upperBound]) + (upperBound < endIndex ? "…" : "") }
}
return String(self)
}
}
"蝙蝠侠喜欢猫女和阿福".limitedLenghtLabelText // "蝙蝠侠喜欢猫女和…"
"Batman喜欢猫女和阿福".limitedLenghtLabelText // "Batman喜欢猫女和…"
Related Topics
Viewdiddisappear Not Called When Use Presentviewcontroller
Opencv Error: Assertion Failed on iOS
Invalid Update: Invalid Number of Sections in Uitableview
Xcode UI Tests Can't Find Views That Are Added Programmatically
iOS App Breakpoints on Running
iOS: Is Possible to Rounder Radius with Different Value in Each Corner
-Costtonode:' Not Sent to Gkgraphnode2D Subclass in Gameplaykit
How to Change Tabbar Icon Color in iOS
How to Set The Date and Time Programmatically in iOS
How to Change Brightness, Contrast and Saturation Using Cicolorcontrols via Uislider with Swift
Conversion from String to Date in Swift Returns Nil
Sorting Nsarray Containing Nsdate Objects
Camera Only Takes Pictures in Portrait Mode Swift
Use Elcimagepickercontroller to Pick Video
Customize Google Maps Blue Dot for Current Location
Retrieve All Child Value to a Label in Table View Cell
Display: Flex; Doesn't Work on iPad (Both Chrome and Safari)