Showing Uilabel's Text

UILabel don't show all text

Just follow the code below.

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;

Can not show my text in UILabel

This is a thread issue. URLSession is is asynchronous, so you have to update the UI in the completionHandler.

let task = URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
//print(data)

if let pocetDatabaze = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) {

self.pocetDatabaze2 = Int(pocetDatabaze as String)!
self.pocetDatabaze3 = String(pocetDatabaze2 as Int)
DispatchQueue.main.async {
self.aktualniPocet.text = pocetDatabaze3
}
}

})

You need a call to DispatchQueue.main because you should update the UI in the main thread. Then you can comment out the other two calls.

Swift: UILabel how to show all text

you can do this by setting numberOfLines to 0

Example

 myLabel.text = "whatever"
myLabel.numberOfLines = 0
myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

And you have so set frame according to it

Refer : to this link

How to show Show more text in uilabel?

Use the following code for for answer.

 - (void)addReadMoreStringToUILabel:(UILabel*)label
{
NSString *readMoreText = @" ...Read More";
NSInteger lengthForString = label.text.length;
if (lengthForString >= 100)
{
NSInteger lengthForVisibleString = 100;
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:label.text];
NSString *trimmedString = [mutableString stringByReplacingCharactersInRange:NSMakeRange(lengthForVisibleString, (label.text.length - lengthForVisibleString)) withString:@""];
NSInteger readMoreLength = readMoreText.length;
NSString *trimmedForReadMore = [trimmedString stringByReplacingCharactersInRange:NSMakeRange((trimmedString.length - readMoreLength), readMoreLength) withString:@""];
NSMutableAttributedString *answerAttributed = [[NSMutableAttributedString alloc] initWithString:trimmedForReadMore attributes:@{
NSFontAttributeName : label.font

}];

UIColor *color = [UIColor colorWithRed:21.0/255.0 green:40.0/255.0 blue:86.0/255.0 alpha:1]; // select needed color
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color, NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)};
NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:attrs];

[answerAttributed appendAttributedString:readMoreAttributed];
label.attributedText = answerAttributed;

UITapGestureRecognizer *readMoreGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(readMoreDidClickedGesture:)];

readMoreGesture.numberOfTapsRequired = 1;
[label addGestureRecognizer:readMoreGesture];

label.userInteractionEnabled = YES;
}
else
{

NSLog(@"No need for 'Read More'...");

}
}

-(void)readMoreDidClickedGesture:(id)sender
{
if(ReadMoretag==1)
{

ReadMoretag=0;

NSString *readMoreText = @" Read Less";
UIColor *color = [UIColor colorWithRed:21.0/255.0 green:40.0/255.0 blue:86.0/255.0 alpha:1]; // select needed color
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:attrs];

NSMutableAttributedString *answerAttributed = [[NSMutableAttributedString alloc] initWithString:StrProfileSummary attributes:@{
NSFontAttributeName : LblProfilEsummary.font

}];

[answerAttributed appendAttributedString:readMoreAttributed];
LblProfilEsummary.attributedText = answerAttributed;

}

else
{
ReadMoretag=1;
[self addReadMoreStringToUILabel:LblProfilEsummary];

}
}

Custom UILabel is not displaying text

To debug, I created a new single view app and added MyLabel.h and MyLabel.m files to project.

I Used Xcode 8 and iPhone 5S simulator.

But the result were same no text was being displayed by MyLabel.

Frustrated me, removed all the code from MyLabel.h and MyLabel.m except properties in MyLabel.h, overall class looked like below:

Header File:

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface MyLabel : UILabel

@property (nonatomic) IBInspectable CGFloat letterSpacing;
@property (nonatomic) IBInspectable CGFloat lineSpacing;

@end

Implementation File:

#import "MyLabel.h"

@implementation MyLabel

@end

Even with above code, no text was displayed by MyLabel.

Now I decided to rename the properties like below:

@property (nonatomic) IBInspectable CGFloat ltrSpacing;
@property (nonatomic) IBInspectable CGFloat lnSpacing;

Surprisingly MyLabel started displaying the text, weird.

Then I re-introduced my logic and everything is working fine.

I think the property names I chose were conflicting with some of UILabel's private properties but I am not sure about the exact reason.

UILabel not showing all text

A bit difficult to know for certain, because you didn't provide a complete working example, but this may fix your issue.

See the comments for changes:

@interface MyTableViewCell ()

@property (strong, nonatomic) UILabel *firstLabel;
@property (strong, nonatomic) UILabel *secondLabel;

@end

@implementation MyTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
[self initialize];
}
return self;
}

- (void)initialize {
[self.contentView setBackgroundColor:[UIColor systemTealColor]];
[self.backgroundView setBackgroundColor:[UIColor systemGrayColor]];

[self.contentView addSubview:self.firstLabel];
[self.contentView addSubview:self.secondLabel];

// not needed
//NSLayoutConstraint *heightConstraint = [self.heightAnchor constraintEqualToConstant:1.0f];
//[heightConstraint setPriority:50];

[NSLayoutConstraint activateConstraints:@[
[self.firstLabel.leadingAnchor constraintEqualToAnchor:self.contentView.layoutMarginsGuide.leadingAnchor],
[self.firstLabel.topAnchor constraintEqualToAnchor:self.contentView.layoutMarginsGuide.topAnchor],
[self.firstLabel.trailingAnchor constraintEqualToAnchor:self.centerXAnchor constant:-4.0f],

[self.secondLabel.leadingAnchor constraintEqualToAnchor:self.centerXAnchor constant:4.0f],
[self.secondLabel.topAnchor constraintEqualToAnchor:self.contentView.layoutMarginsGuide.topAnchor],
[self.secondLabel.trailingAnchor constraintEqualToAnchor:self.contentView.layoutMarginsGuide.trailingAnchor],

[self.contentView.layoutMarginsGuide.bottomAnchor constraintGreaterThanOrEqualToAnchor:self.firstLabel.bottomAnchor constant:20.0f],
[self.contentView.layoutMarginsGuide.bottomAnchor constraintGreaterThanOrEqualToAnchor:self.secondLabel.bottomAnchor constant:20.0f],

// not needed
//heightConstraint
]];
}

- (UILabel *)firstLabel {
if (!self->_firstLabel) {
self->_firstLabel = [[UILabel alloc] init];
self->_firstLabel.translatesAutoresizingMaskIntoConstraints = NO;
self->_firstLabel.numberOfLines = 0;
self->_firstLabel.userInteractionEnabled = NO;

// not needed
//self->_firstLabel.contentMode = UIViewContentModeScaleToFill;
//[self->_firstLabel setContentHuggingPriority:251 forAxis:UILayoutConstraintAxisHorizontal];
//[self->_firstLabel setContentHuggingPriority:251 forAxis:UILayoutConstraintAxisVertical];
//[self->_firstLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
//[self->_firstLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

self->_firstLabel.textAlignment = NSTextAlignmentNatural;

// word-wrapping, not truncating
//self->_firstLabel.lineBreakMode = NSLineBreakByTruncatingTail;
self->_firstLabel.lineBreakMode = NSLineBreakByWordWrapping;

self->_firstLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
self->_firstLabel.adjustsFontSizeToFitWidth = NO;
self->_firstLabel.backgroundColor = [UIColor orangeColor];
}
return self->_firstLabel;
}

- (UILabel *)secondLabel {
if (!self->_secondLabel) {
self->_secondLabel = [[UILabel alloc] init];
self->_secondLabel.translatesAutoresizingMaskIntoConstraints = NO;
self->_secondLabel.numberOfLines = 0;
self->_secondLabel.userInteractionEnabled = NO;

// not needed
//self->_secondLabel.contentMode = UIViewContentModeScaleToFill;
//[self->_secondLabel setContentHuggingPriority:251 forAxis:UILayoutConstraintAxisHorizontal];
//[self->_secondLabel setContentHuggingPriority:251 forAxis:UILayoutConstraintAxisVertical];
//[self->_secondLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
//[self->_secondLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

self->_secondLabel.textAlignment = NSTextAlignmentNatural;

// word-wrapping, not truncating
//self->_secondLabel.lineBreakMode = NSLineBreakByTruncatingTail;
self->_secondLabel.lineBreakMode = NSLineBreakByWordWrapping;

self->_secondLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
self->_secondLabel.adjustsFontSizeToFitWidth = NO;
self->_secondLabel.backgroundColor = [UIColor yellowColor];
}
return self->_secondLabel;
}

- (void)setData:(MyData *)data {
self.firstLabel.text = data.first;
self.secondLabel.text = data.second;

// this is needed
[self.firstLabel layoutIfNeeded];
[self.secondLabel layoutIfNeeded];

// not needed
//[self invalidateIntrinsicContentSize];
}

@end

UILabel custom Text

You can use NSTextAttachment for that behaviour. I modify this for position of attachment.

All code :

  @IBOutlet weak var lbl: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

let string = "Urban points users average montly saving is "


let normalNameString = NSMutableAttributedString.init(string: string)

let attachment = NSTextAttachment()
attachment.image = imageHelper.pgImage(textValue: "QAR 115 ", lbl: lbl)

attachment.bounds = CGRect(x: 0, y: (lbl.font.capHeight - attachment.image!.size.height).rounded() / 2, width: attachment.image!.size.width, height: attachment.image!.size.height)


normalNameString.append(NSAttributedString(attachment: attachment))
normalNameString.append(NSAttributedString(string: "You have saved "))

let attachment2 = NSTextAttachment()
attachment2.image = imageHelper.pgImage(textValue: "QAR 29",textColor: UIColor.yellow,backgroundColor: UIColor.black , lbl: lbl)
attachment2.bounds = CGRect(x: 0, y: (lbl.font.capHeight - attachment2.image!.size.height).rounded() / 2, width: attachment2.image!.size.width, height: attachment2.image!.size.height)

normalNameString.append(NSAttributedString(attachment: attachment2))
normalNameString.append(NSAttributedString(string: " this month"))

lbl.attributedText = normalNameString
}

}

class imageHelper{
static func pgImage(textValue:String,textColor : UIColor = UIColor.white , backgroundColor : UIColor = UIColor.red,lbl : UILabel) ->UIImage{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: (textValue as NSString).size(withAttributes: [NSAttributedString.Key.font : lbl.font!]).width, height: lbl.frame.size.height))
label.font = lbl.font
label.textAlignment = .center
label.textColor = textColor
label.backgroundColor = backgroundColor
label.layer.borderColor = UIColor.darkGray.cgColor
label.layer.borderWidth = 1
label.layer.cornerRadius = label.frame.size.height/2
label.layer.masksToBounds = true
label.text = textValue
label.numberOfLines = 1

UIGraphicsBeginImageContextWithOptions(label.bounds.size, false,UIScreen.main.scale)
label.layer.render(in: UIGraphicsGetCurrentContext()!)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}

And the result is :
image here



Related Topics



Leave a reply



Submit