为手写UIButton、UITextField设置边框样式

本文介绍了如何使用Objective-C自定义iOS应用中的UIButton和UITextField控件,通过分类方式提供便捷的初始化及属性设置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为为常见控件,需要经常调用创建的缘故,故可以将之写为分类。

并写一个类方法方便其调用,代码如下:(UIButton)

//

//  UIButton+MY.h

//  Copyright © 2016 oh. All rights reserved.

#import <UIKit/UIKit.h>


@interface UIButton (MY)

+(UIButton *)buttonSetAttrs;  //类方法,用以设置按键属性.

@end

//

//  UIButton+MY.m

//  Copyright © 2016 oh. All rights reserved.

#import "UIButton+MY.h"


@implementation UIButton (MY)

+(UIButton *)buttonSetAttrs

{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];//按键类型设置

    [button setTitleColor:[UIColor orangeColorforState:UIControlStateNormal];//按键文字颜色设置(普通状态)

    [button setTitleColor:[UIColor grayColorforState:UIControlStateDisabled];//按键文字颜色设置(不可用状态)

    button.titleLabel.font = [UIFont systemFontOfSize:14];//按键文字的字体大小设置

    button.layer.borderWidth = 1.0f; //按键边框宽度设置

    button.layer.borderColor = [UIColor lightGrayColor].CGColor;//按键边框颜色设置

    button.layer.cornerRadius = 2;//设置按键边框圆角处的半径

    return button;

}

@end


以上,即能够将所需按键创建出来并赋予它一些基本的属性。


(UITextField):

//  UITextField+MY.h

//  Copyright © 2016 oh. All rights reserved.

#import <UIKit/UIKit.h>


@interface UITextField (MY)

+(UITextField *)textFieldSetAttrs; //类方法,用以设置textField属性

@end


//  UITextField+MY.m

//  Copyright © 2016 oh. All rights reserved.

#import "UITextField+MY.h"


@implementation UITextField (MY)

+(UITextField *)textFieldSetAttrs

{

    UITextField *textField = [[UITextField alloc]init];

    textField.font = [UIFont systemFontOfSize:14];  //设置textField的字体大小

    textField.textColor = [UIColor blackColor];  //设置textField的文字颜色

    textField.textAlignment = NSTextAlignmentCenter;  //设置textField为居中显示

    textField.layer.borderWidth = 1.0f;  //设置textField的边框宽度

    textField.layer.cornerRadius = 5;   //设置textField边框的圆角半径

    textField.layer.borderColor =[UIColor lightGrayColor].CGColor;//设置textField的边框颜色

    return textField;

}


@end



*注意,相比UITextField、UIButton是有不同的状态的,即普通、高亮、不可用等。因此设置UIButton的字体颜色、文字图片时切记应该与其所处的状态联系起来,没有状态限制则设置无效。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值