UILabel текстовое поле - PullRequest
       47

UILabel текстовое поле

297 голосов
/ 13 августа 2010

Я пытаюсь установить левую вставку / поле UILabel и не могу найти способ сделать это. У метки есть задний фон, поэтому просто смена источника не поможет. Было бы идеально вставить текст с помощью 10px или около того с левой стороны.

Ответы [ 38 ]

4 голосов
/ 19 июля 2018

Swift 4 версия блябтрой решение

let leadingMargin: CGFloat = 10
let trailingMargin: CGFloat = 10

let style = NSMutableParagraphStyle()
style.alignment = .justified
style.firstLineHeadIndent = leadingMargin
style.headIndent = leadingMargin
style.tailIndent = trailingMargin

label.attributedText = NSAttributedString(string: "Label with margins", 
                                          attributes: [NSAttributedStringKey.paragraphStyle: style])
4 голосов
/ 14 сентября 2016

ответ Блябтроя, преобразованный в Swift (не требует подклассов)

let style: NSMutableParagraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
style.alignment = .Justified
style.firstLineHeadIndent = 10.0
style.headIndent = 10.0
style.tailIndent = -10.0
let attrText: NSAttributedString = NSAttributedString(string: title, attributes: [NSParagraphStyleAttributeName:style])
let label: UILabel = UILabel(frame: someFrame)
label.numberOfLines = 0
label.attributedText = attrText
3 голосов
/ 08 октября 2016

Swift 3 & AutoLayout совместимая версия:

class InsetLabel: UILabel {

    var insets = UIEdgeInsets()

    convenience init(insets: UIEdgeInsets) {
        self.init(frame: CGRect.zero)
        self.insets = insets
    }

    convenience init(dx: CGFloat, dy: CGFloat) {
        let insets = UIEdgeInsets(top: dy, left: dx, bottom: dy, right: dx)
        self.init(insets: insets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

    override var intrinsicContentSize: CGSize  {
        var size = super.intrinsicContentSize
        size.width += insets.left + insets.right
        size.height += insets.top + insets.bottom
        return size
    }
}
3 голосов
/ 04 марта 2019

Это самое простое решение, которое я нашел для этого:

Swift 4

class CustomLabel: UILabel{
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)))
    }
}

Убедитесь, что в коде, а также в раскадровке установлены метки CustomLabel класса .

2 голосов
/ 18 марта 2015

Xcode 6.1.1. Решение Swift с расширением.

Имя файла может быть примерно таким:

2 голосов
/ 19 февраля 2016

без подклассов и всего такого джаза .. я сделал это динамически:

[cell.textLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[cell.textLabel constraintTrailingEqualTo:cell.contentView constant:-100];

часть ограничения - это просто простая оболочка кода (у нас есть те же методы для добавления отступов сверху / снизу / слева / справа). Я открою исходный текст всей оболочки, если я получу достаточно любви:

- (id)constraintTrailingEqualTo:(UIView *)toView constant:(CGFloat)constant
{
    NSLayoutConstraint *cn = [NSLayoutConstraint constraintWithItem:self
                                                          attribute:NSLayoutAttributeTrailing
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:toView
                                                          attribute:NSLayoutAttributeTrailing
                                                         multiplier:1 constant:constant];

    [toView addConstraint:cn];
    return self;
}

(обратите внимание, я сделал это в контексте

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath;

вам может потребоваться позвонить [self setNeedsLayout]; в зависимости от вашего контекста.

2 голосов
/ 09 мая 2017
#import "E_LabelWithPadding.h"
#define padding UIEdgeInsetsMake(2, 0, 2, 0)
#define padding1 UIEdgeInsetsMake(0, 0, 0, 0)
@implementation E_LabelWithPadding
- (void)drawTextInRect:(CGRect)rect {
if (![self.text isEqualToString:@""]) {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding)];
}else {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding1)];
}

}

- (CGSize) intrinsicContentSize {
if (![self.text isEqualToString:@""]) {
    CGSize superContentSize = [super intrinsicContentSize];
    CGFloat width = superContentSize.width + padding.left + padding.right;
    CGFloat height = superContentSize.height + padding.top + padding.bottom;
    return CGSizeMake(width, height);
}else {
    CGSize superContentSize = [super intrinsicContentSize];
    CGFloat width = superContentSize.width + padding1.left + padding1.right;
    CGFloat height = superContentSize.height + padding1.top + padding1.bottom;
    return CGSizeMake(width, height);
}

}

- (CGSize) sizeThatFits:(CGSize)size {
if (![self.text isEqualToString:@""]) {
    CGSize superSizeThatFits = [super sizeThatFits:size];
    CGFloat width = superSizeThatFits.width + padding.left + padding.right;
    CGFloat height = superSizeThatFits.height + padding.top + padding.bottom;
    return CGSizeMake(width, height);
}else {
    CGSize superSizeThatFits = [super sizeThatFits:size];
    CGFloat width = superSizeThatFits.width + padding1.left + padding1.right;
    CGFloat height = superSizeThatFits.height + padding1.top + padding1.bottom;
    return CGSizeMake(width, height);
}

}

@end
0 голосов
/ 07 ноября 2018

Я решил это с помощью xcode builder (но, конечно, этого можно добиться с помощью swift, используя ограничения):

Просто создайте UIView соответствующего размера и добавьте в это представление дочерний элемент типа UILabel

и все, у вас есть отступы :)

xcode builder solution

0 голосов
/ 12 февраля 2015

Это самый простой способ, который я нашел. Это работает как шарм для меня.

UIView *titleSection = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 100)];
[titleSection addSubview:titleSection];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectInset(titleSection.frame, PADDING, 0)];
[titleSection addSubview:label];
0 голосов
/ 25 сентября 2013

Установите для свойства textAlignment метки значение NSTextAlignmentRight и увеличьте его ширину.

...