Подтвердить что ты не робот

Как добавить padding-left на UILabel, созданный программно?

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

- (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;
}

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

4b9b3361

Ответ 1

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

-  (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];

}

Ответ 2

Полный список доступных решений см. в этом ответе: поля текста 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

Ответ 3

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

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

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

Ответ 4

Установите 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

Ответ 5

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

- (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;
}

Ответ 6

Вы можете создать подкласс 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;
}

Ответ 7

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

headerLabel.text = [NSString stringWithFormat:@" %@",
                    [[_months objectAtIndex:section] objectForKey:@"name"]];

Ответ 8

Вместо этого вы можете использовать UITextView. Я сделал это в Cocoa, но я уверен, что он переводит 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];