关闭

UITextField设置padding

164人阅读 评论(0) 收藏 举报
分类:

有时为了美化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];3333
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:291119次
    • 积分:4891
    • 等级:
    • 排名:第5801名
    • 原创:92篇
    • 转载:762篇
    • 译文:4篇
    • 评论:16条
    最新评论