【问题标题】:Change border width for multiple UITextFields更改多个 UITextField 的边框宽度
【发布时间】:2016-07-25 02:36:41
【问题描述】:

我在项目中的每个 UIViewController 上使用 5 到 7 个 UITextField。我想为所有这些设置边框宽度。我知道更改UITextField边框宽度的代码:

textField.layer.borderWidth=2.0f;

但是对于每一个UITextField,我都需要这样做。有什么简单的方法可以实现。

【问题讨论】:

  • 扩展 UITextField 并在任何需要的地方使用该文本字段...
  • 为 UITextfield 创建一个类别以进行此类自定义
  • 我同意@MuhammadAdnan,创建扩展(或Objective-C 中的类别)是最好的选择。

标签: ios objective-c uitextfield


【解决方案1】:

您可以使用该类别对 UITextField 进行全局设置,如下所示:

对于创建类别检查这个答案:How to give padding to UITextField in iOS?

UITextField+setBorder.h

#import <UIKit/UIKit.h>

@interface UITextField (setBorder)


-(CGRect)textRectForBounds:(CGRect)bounds;
-(CGRect)editingRectForBounds:(CGRect)bounds;
- (void)setBorderForColor:(UIColor *)color
                    width:(float)width
                   radius:(float)radius;
@end

UITextField+setBorder.m

#import "UITextField+setBorder.h"

@implementation UITextField (setBorder)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
-(CGRect)textRectForBounds:(CGRect)bounds {


     [self setBorderForColor:[UIColor redColor] width:5 radius:0];
    return CGRectMake(bounds.origin.x , bounds.origin.y ,
                      bounds.size.width , bounds.size.height );  // here you can make coercer position change
}
-(CGRect)editingRectForBounds:(CGRect)bounds {



    return [self textRectForBounds:bounds];
}


- (void)setBorderForColor:(UIColor *)color
                    width:(float)width
                   radius:(float)radius
{
    self.layer.cornerRadius = radius;
    self.layer.masksToBounds = YES;
    self.layer.borderColor = [color CGColor];
    self.layer.borderWidth = width;
}

输出是

【讨论】:

  • :: 抱歉,我是 iOS 新手,尽管我使用了您的代码。我想我应该为每个文本字段调用该方法
  • 你不需要在创建一个类别后调用这个方法你只需要复制并过去它的 h 和 m 文件我的代码不需要做任何事情
  • 我为您的代码添加了边框样式,因为我需要这样的 UITextBorderStyleRoundedRect: - (void)setBorderForColor:(UIColor*)color width:(float)width radius:(float)radius borderStyle:(UITextBorderStyle)borderStyle .但边框样式没有改变
【解决方案2】:

U 可以赋值 textField.layer.borderWidth=2.0f;在 NSObject 类中,您可以在需要时继承该类

【讨论】:

    【解决方案3】:

    创建 UITextField 的类子类并为子类中的边框宽度和颜色编写代码的最佳方法。并将您的文本字段的超类提供给创建的类。您无需一次又一次地编写代码。

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 1970-01-01
      • 2017-12-29
      • 2013-09-25
      • 2021-12-30
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2021-04-03
      相关资源
      最近更新 更多