since.2006  

有时为了美化UITextField样式会使用自定义背景图片而将本身的边框隐藏,这时基本上光标的位置都不会很合适,而UITextField默认不可以设置padding,咱们可以自定义一个子类实现padding。

//
//  UITextFieldEx.h
//

#import <Foundation/Foundation.h>

@interface UITextFieldEx : UITextField {
    
    BOOL isEnablePadding;
    float paddingLeft;
    float paddingRight;
    float paddingTop;
    float paddingBottom;
    
}

- (void)setPadding:(BOOL)enable top:(float)top right:(float)right bottom:(float)bottom left:(float)left;

@end
//  UITextFieldEx.m

#import "UITextFieldEx.h"

@implementation UITextFieldEx

- (void)setPadding:(BOOL)enable top:(float)top right:(float)right bottom:(float)bottom left:(float)left {
    isEnablePadding = enable;
    paddingTop = top;
    paddingRight = right;
    paddingBottom = bottom;
    paddingLeft = left;
}

- (CGRect)textRectForBounds:(CGRect)bounds {
    if (isEnablePadding) {
        return CGRectMake(bounds.origin.x + paddingLeft, 
                          bounds.origin.y + paddingTop, 
                          bounds.size.width - paddingRight, bounds.size.height - paddingBottom);
    } else {
        return CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
    }
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}

@end

调用方法:

UITextFieldEx *iptMsg = [[UITextFieldEx alloc]initWithFrame:CGRectMake(20, 25, 331, 46)];
[iptMsg setPadding:YES top:12 right:18 bottom:12 left:10];
iptMsg.borderStyle = UITextBorderStyleNone;
UIColor *iptMsgBg = [[UIColor alloc]initWithPatternImage:[UIImage imageNamed:@"chat_bottom_textfield.png"]];
iptMsg.backgroundColor = iptMsgBg;
[self.view addSubview:iptMsg];
标签:

Posted by hee at 11:03 AM | Permalink | 评论(0) | iOS

请输入名称
请输入邮件地址

 

    请输入邮件地址