Reputation: 589
How can I add padding to the UIlabel
text that created programmatically?
NSArray *collectionViewArrayTitle = _titleArray[collectionView.index];
NSString *title= collectionViewArrayTitle[indexPath.item];
newslabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 80, 130, 50)];
_newslabel.textColor=[UIColor whiteColor];
_newslabel.backgroundColor=[UIColor blackColor] ;
_newslabel.alpha=1.0f;
_newslabel.text=title;
_newslabel.tag=collectionView.index;
_newslabel.lineBreakMode=NSLineBreakByTruncatingTail;
_newslabel.numberOfLines=4;
Upvotes: 0
Views: 596
Reputation: 1371
NSLayoutConstrains are Obj-C objects. You can also create them programatically. Or you can also create them in the Storyboard and drag an outlet to your controller and manipulate them on code.
On code you can handle that with the NSConstrain class or you can use the VFL (visual format language). In any case, check Apple's documentation for it. Once you get the handle of it, it's quite straightforward.
Upvotes: 1
Reputation: 7583
The best way to add 'padding' to your labels is to make a subclass of UILabel and add the edgeInsets property.
CustomLabel.h
#import <UIKit/UIKit.h>
@interface CustomLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets edgeInsets;
@end
CustomLabel.m
#import "CustomLabel.h"
@implementation CustomLabel
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 0); //customize padding here
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
@end
Another way of adding padding is to use a second layer. This may be a lot easier to accomplish but is imo not the most clean way to deal with it. You can add a UIView with the size of the label and then adjust that frame with some padding. Then you can add the intended UILabel to this view and play with the origins to get the right padding this way.
Upvotes: 1