美文网首页
iOS开发,简化手写代码,创建各种View(label,butt

iOS开发,简化手写代码,创建各种View(label,butt

作者: 小江9527 | 来源:发表于2019-03-06 14:46 被阅读0次

对于手写代码来说,创建相同的view是很烦的,copy是无聊的工作。
以前创建view对象是这样写:

    UILabel *label1 = [[UILabel alloc] init];
    label1.text = @"label1";
    label1.textColor = [UIColor redColor];
    [self.view addSubview:label1];
    
    UILabel *label2 = [[UILabel alloc] init];
    label2.text = @"label2";
    label2.textColor = [UIColor redColor];
    [self.view addSubview:label2];

    UITextField *tf = [[UITextField alloc] init];
    tf.text = @"tf";
    tf.delegate = self;
    [self.view addSubview:tf];

现在可以这样写:

   UILabel *label3 = [self.view addLabel:@"label3"];
   UILabel *label4 = [self.view addLabel:@"label4" color:[UIColor redColor]];
   UITextField *tf = [self.view addTextField:@"text" delegate:self];

写过代码的人都知道,第二种写法可以更快,代码复用性更高。
其实就是快捷了一点,反正我是喜欢这样。

可以很简单的看下代码。

@interface UIView (Add)
/**
 当前View添加label

 @return 返回Label
 */
-(UILabel *)addLabel;

/**
 当前View添加Label,设置文字

 @param text 显示文字
 @return 返回Label
 */
-(UILabel *)addLabel:(nullable NSString *)text;

/**
 当前View添加Label,设置文字、字体

 @param text 显示文字
 @param font 字体
 @return 返回Label
 */
-(UILabel *)addLabel:(nullable NSString *)text font:(nullable UIFont *)font;

/**
 当前View添加Label,设置文字、颜色

 @param text 文字
 @param color 颜色
 @return 返回Label
 */
-(UILabel *)addLabel:(nullable NSString *)text color:(nullable UIColor *)color;

/**
 当前View添加Label,设置文字、字体、颜色

 @param text 文字
 @param font 字体
 @param color 颜色
 @return 返回Label
 */
-(UILabel *)addLabel:(nullable NSString *)text font:(nullable UIFont *)font color:(nullable UIColor *)color;


#pragma mark - UITextField Add
/**
 当前UIView添加UITextField
 
 @return 返回UITextField对象
 */
-(UITextField *)addTextField;
@end

很简单,就是给UIView添加了一个Category。

想用的可以使用在Podfile文件添加如下代码

pod 'UIView+Add'

有不足的地方可以留言,一起探讨。

希望对你们有帮助!

相关文章

网友评论

      本文标题:iOS开发,简化手写代码,创建各种View(label,butt

      本文链接:https://www.haomeiwen.com/subject/bwitpqtx.html