Как добавить padding-left на UILabel, созданный программно? - PullRequest
21 голосов
/ 29 февраля 2012

Я знаю, что это нубский вопрос, но ... У меня есть эти ярлыки на табличном виде, но текст полностью сжат слева Я хочу добавить немного отступов. Как мне это сделать?

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section  {

    UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(10,0,300,60)] autorelease];

    UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];

    headerLabel.backgroundColor = [UIColor colorWithHexString:[[_months objectAtIndex:section] objectForKey:@"color"]];
    headerLabel.font = [UIFont boldSystemFontOfSize:18];
    headerLabel.frame = CGRectMake(0,0,400,30);
    headerLabel.text =  [[_months objectAtIndex:section] objectForKey:@"name"];

    headerLabel.textColor = [UIColor whiteColor];


    [customView addSubview:headerLabel];

    return customView;
}

любая помощь высоко ценится! Спасибо!

Ответы [ 8 ]

40 голосов
/ 10 июля 2013

Полный список доступных решений см. В следующем ответе: Текстовое поле UILabel


Самый гибкий подход для добавления отступов в UILabel - это создать подкласс UILabel и добавить свойство edgeInsets. Затем вы установите нужные вставки, и этикетка будет нарисована соответствующим образом.

OSLabel.h

#import <UIKit/UIKit.h>

@interface OSLabel : UILabel

@property (nonatomic, assign) UIEdgeInsets edgeInsets;

@end

OSLabel.m

#import "OSLabel.h"

@implementation OSLabel

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return self;
}

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}

@end
17 голосов
/ 08 марта 2013

Вы можете просто добавить пробел в начале текста;

[NSString stringWithFormat:@"  %@",text];

Это «злой» способ добавить «отступы», но это может помочь.

14 голосов
/ 08 мая 2012

Я нашел лучший способ сделать это:

-  (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section  {

    CGRect frame = CGRectMake(0, 0, 320, 25);
    UIView *customView = [[UIView alloc] initWithFrame:frame];
    UILabel *sectionTitle = [[UILabel alloc] init];
    [customView addSubview:sectionTitle]; 
    customView.backgroundColor = [UIColor redColor];

    frame.origin.x = 10; //move the frame over..this adds the padding!
    frame.size.width = self.view.bounds.size.width - frame.origin.x;

    sectionTitle.frame = frame;
    sectionTitle.text = @"text";
    sectionTitle.font = [UIFont boldSystemFontOfSize:17];
    sectionTitle.backgroundColor = [UIColor clearColor];
    sectionTitle.textColor = [UIColor whiteColor];

    [sectionTitle release];

    tableView.allowsSelection = NO;

    return [customView autorelease];

}
8 голосов
/ 29 февраля 2012

Установите backgroundColor в customView также

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CGRect frame = tableView.bounds;
    frame.size.height = HEADER_HEIGHT;
    UIView* customView = [[[UIView alloc] initWithFrame:frame] autorelease];
    customView.backgroundColor = [UIColor redColor];    

    UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] autorelease];     
    // Orientation support   
    headerLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;    
    headerLabel.backgroundColor = [UIColor redColor];
    headerLabel.font = [UIFont boldSystemFontOfSize:18];
    headerLabel.text = @"My Text Label";        
    headerLabel.textColor = [UIColor whiteColor];

    [customView addSubview:headerLabel];

    return customView;    
}

Старайтесь не кодировать магические числа: (добавьте их в начало файла)

#define HEADER_HEIGHT 60.0f
#define LABEL_PADDING 10.0f

Должен дать это preview

2 голосов
/ 10 апреля 2015

Вы можете создать подкласс UILabel и переопределить intrinsicContentSize и - (CGSize)sizeThatFits:(CGSize)size:

- (CGSize) intrinsicContentSize
{
    CGSize parentSize = [super intrinsicContentSize];
    parentSize.width += 2*PADDING_VALUE;
    return parentSize;
}

- (CGSize)sizeThatFits:(CGSize)size
{
    CGSize parentSize = [super sizeThatFits:size];
    parentSize.width += 2*PADDING_VALUE;
    return parentSize;
}
2 голосов
/ 29 февраля 2012

Попробуйте следующее и поиграйте с отступами и т. Д.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section  {

    CGFloat headerHeight = 60, padding = 10;

    UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,320,headerHeight)] autorelease];
    customView.backgroundColor = [UIColor colorWithHexString:[[_months objectAtIndex:section] objectForKey:@"color"]];

    CGRect frame = CGRectMake(padding,padding,320 - 2*padding,headerHeight-2*padding);

    UILabel *headerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];

    headerLabel.font = [UIFont boldSystemFontOfSize:18];
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.text =  [[_months objectAtIndex:section] objectForKey:@"name"];

    headerLabel.textColor = [UIColor whiteColor];

    [customView addSubview:headerLabel];

    return customView;
}
0 голосов
/ 29 февраля 2012

Вместо этого вы можете использовать UITextView.Я сделал это в Какао, но я уверен, что это переводится в UITextView:

    NSTextView *headerLabel = [[[NSTextView alloc] initWithFrame:NSMakeRect(20.0, 20.0, 400.0, 20.0)] autorelease];
[headerLabel setBackgroundColor: [NSColor redColor]];
[headerLabel setString: @"Testing Stuff"];
[headerLabel setTextColor:  [NSColor whiteColor]];

NSSize txtPadding; 
txtPadding.width = 20.0;
txtPadding.height = 0.0;
[headerLabel setTextContainerInset:txtPadding];

[[mainWin contentView] addSubview:headerLabel];
0 голосов
/ 29 февраля 2012

Правда, это немного неточно и хакерски, но вы всегда можете добавить пробел перед названием месяца, например:

headerLabel.text = [NSString stringWithFormat:@" %@",
                    [[_months objectAtIndex:section] objectForKey:@"name"]];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...