自定義UITextField

原文
目的是實現如下的效果:


UITextField的leftView是自定義的UIView,其中:
1、包含一個居中顯示的icon,并且上,左,下各有1px的間隙
2、左上和左下是圓角,右邊沒有圓角

居中展示icon

關鍵是leftView不是UIImageView,而是把UIImageView設置為subview

CGFloat height = frame.size.height;
        
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, height - 1, height - 2)];
        
UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:iconName]];
icon.frame = CGRectMake(height / 4, height / 4, height / 2, height / 2);
[leftView addSubview:icon];

上面的代碼,使icon在leftView居中顯示

制造1px間隙

top和bottom的間隙很容易做,只要令leftView的height比UITextField的height少2,然后y設置為1
左側的間隙比較麻煩,首先將width設置為比UITextField的width少1。但是直接設置x為1無效,需要override以下方法:

-(CGRect) leftViewRectForBounds:(CGRect)bounds {  
    CGRect iconRect = [super leftViewRectForBounds:bounds];  
    iconRect.origin.x += 1;  
    return iconRect;  
}  

制造部分圓角
制造所有的圓角比較簡單,只需要:

self.layer.cornerRadius = 5;

但是要制造部分圓角,就比較麻煩:

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:leftView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(5, 5)];  
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];  
maskLayer.frame = leftView.bounds;  
maskLayer.path = maskPath.CGPath;  
leftView.layer.mask = maskLayer; 

創建陰影

self.layer.shadowColor = [UIColor colorWithRed:132/255.0f green:214/255.0f blue:219/255.0f alpha:1.0f].CGColor;
self.layer.shadowOpacity = 0.5;
self.layer.shadowOffset = CGSizeMake(3, 3);

完整的代碼

@implementation LosTextField

-(id)initWithFrame:(CGRect)frame Icon:(NSString*)iconName
{
    self = [super initWithFrame:frame];
    if (self) {
        
        CGFloat height = frame.size.height;
        
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, height - 1, height - 2)];
        leftView.backgroundColor = [UIColor colorWithRed:132/255.0f green:214/255.0f blue:219/255.0f alpha:1.0f];
        
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:iconName]];
        icon.frame = CGRectMake(height / 4, height / 4, height / 2, height / 2);
        [leftView addSubview:icon];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:leftView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(5, 5)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = leftView.bounds;
        maskLayer.path = maskPath.CGPath;
        leftView.layer.mask = maskLayer;
        
        self.leftView = leftView;
        self.leftViewMode = UITextFieldViewModeAlways;
    }
    return self;
}

-(CGRect) leftViewRectForBounds:(CGRect)bounds {
    CGRect iconRect = [super leftViewRectForBounds:bounds];
    iconRect.origin.x += 1;
    return iconRect;
}

@end
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容