UITextField上的自定义“占位符”意外截断

时间:2013-10-13 20:30:19

标签: ios objective-c uitextfield placeholder

我正在尝试通过添加UILabel作为文本字段的子视图来创建具有各种持久“占位符”的文本字段。但是,我的标签一直被截断,我无法弄清楚原因。任何建议都非常感谢!

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

这是我的代码:

#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

0 个答案:

没有答案