0

我正在尝试通过添加 UILabel 作为文本字段的子视图来创建具有持久性“占位符”的文本字段。但是,我的标签一直被截断,我不知道为什么。非常感谢任何建议!

这是我目前得到的(应该说“名字”: 当前的

这是我的代码:

#import "LabeledTextField.h"

@interface PlaceholderLabel : UILabel
@end

@implementation PlaceholderLabel

-(void)drawTextInRect:(CGRect)rect
{
    UIEdgeInsets insets = {0, 10, 0, 0};

    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

@end

@interface LabeledTextField ()

@property (nonatomic) PlaceholderLabel *placeholderLabel;

@end

@implementation LabeledTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _placeholderLabel = [[PlaceholderLabel alloc] initWithFrame:CGRectMake(10, [self frame].size.height/2, 0, 0)];
        [_placeholderLabel setBackgroundColor:UIColorFromRGB(0xdedede)];
        [_placeholderLabel setTextColor:UIColorFromRGB(0x787878)];
        [_placeholderLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:kTextFieldPlaceholderFontSize]];
        [_placeholderLabel setLineBreakMode:NSLineBreakByTruncatingTail];
        [_placeholderLabel setNumberOfLines:1];
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    [self setLeftView:_placeholderLabel];
}

-(void)drawPlaceholderInRect:(CGRect)rect
{
    return;
}

-(void)setPlaceholder:(NSString *)placeholder
{
    [_placeholderLabel setText:placeholder];
    [_placeholderLabel sizeToFit];
}

-(CGRect)leftViewRectForBounds:(CGRect)bounds
{
    CGRect frame = [_placeholderLabel frame];
    frame.origin.y = (self.frame.size.height - frame.size.height)/2;
    frame.size = [[_placeholderLabel text] sizeWithFont:[UIFont fontWithName:@"HelveticaNeue" size:kTextFieldPlaceholderFontSize]];
    return frame;
}
@end
4

0 回答 0