自定义UITextField

一、自定义UITextField;

#import "KCTextField.h"
#define kMinScreenWidth 320.0f
#define kFont (([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0f && CGRectGetWidth([UIScreen mainScreen].bounds) >= kMinScreenWidth) ? 14.0f : 12.0f)

@interface KCTextField ()

@property (nonatomic,strong) UIView *leftSubView;
@end

@implementation KCTextField

- (instancetype)initWithFrame:(CGRect)frame leftViewImage:(NSString *)ImageName placeHolder:(NSString *)placeHolder andplaceHolder:(NSString *)andplaceHolder
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor whiteColor];
        self.borderStyle = UITextBorderStyleNone;
        self.leftViewMode = UITextFieldViewModeAlways;
        self.rightViewMode = UITextFieldViewModeAlways;
        self.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.font = [UIFont systemFontOfSize:kFont];
        
        UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(6, 6, 18, 18)];
        leftView.image = [UIImage imageNamed:ImageName];
        
        self.placeholder = placeHolder;
        self.autocorrectionType = UITextAutocorrectionTypeNo;//关闭自动联想
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;//关闭首字母大写
        
        NSMutableParagraphStyle *style = [self.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
        style.minimumLineHeight = self.font.lineHeight - (self.font.lineHeight - [UIFont systemFontOfSize:12.0f].lineHeight) / 2.0;
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.placeholder];
        if (andplaceHolder && andplaceHolder.length > 0)
        {
            NSRange placeHolderRange = [self.placeholder rangeOfString:andplaceHolder];
            [attrString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11.0f],NSParagraphStyleAttributeName:style} range:placeHolderRange];
            [attrString addAttributes:@{NSFontAttributeName:self.font,NSParagraphStyleAttributeName:style} range:NSMakeRange(0, attrString.length-placeHolderRange.length)];
        }else{
            [attrString addAttributes:@{NSFontAttributeName:self.font,NSParagraphStyleAttributeName:style} range:NSMakeRange(0, attrString.length)];
        }
        
        self.attributedPlaceholder = attrString;
        self.leftView = self.leftSubView;
        [self.leftSubView addSubview:leftView];
    }
    return self;
}
- (UIView *)leftSubView
{
    if (!_leftSubView)
    {
        _leftSubView = ({
            UIView *leftSubView = [[UIView alloc] initWithFrame:({
                CGRect frame = CGRectMake(0, 0, 30, 30);
                frame;
            })];
            
            leftSubView;
        });
    }
    return _leftSubView;
}

总结,奇怪的是IOS7UITextfield的attributedPlaceholder无法设置成功;无奈之下才在设置UITextfield字体时判断了设备当前的系统版本以及当前设备。



你可能感兴趣的:(自定义UITextField)