【问题标题】:Add opaque subview to UITextField将不透明子视图添加到 UITextField
【发布时间】:2013-02-19 15:40:21
【问题描述】:

我有一个UITextField 的子类,我正在尝试向它添加一个不透明的子视图。但是,当我输入UITextField 时,它看起来是透明的,我可以看到视图后面的文本。如何使视图完全不透明?这是初始化子类并添加视图的代码。

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
       _dropdownIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ab- dropdown-on"]];     
        dropdownIcon.backgroundColor = [UIColor blackColor];
       _dropdownIcon.frame = CGRectMake(self.frame.size.width-DROPDOWN_ICON_SIZE,0,DROPDOWN_ICON_SIZE,DROPDOWN_ICON_SIZE);
       [self addSubview:_dropdownIcon];
   }
    return self;
}

【问题讨论】:

  • 当您开始输入时,我相信文本编辑器字段被放置在顶部 - 我会在超级视图中将视图分层 - 或者使用 UITextField 子视图和不透明视图创建一个 MyTextfield 类。
  • 没试过,但是setBackgroundColorsetBackground 呢?

标签: ios objective-c uiview uitextfield opacity


【解决方案1】:

您的子类需要重写 -textRectForBounds: 方法以返回您想要绘制文本的实际区域,例如

- (CGRect)textRectForBounds:(CGRect)bounds
{
    CGRect textRect = [super textRectForBounds:bounds];
    textRect.size.width -= 30; // or however wide your control is—play with this value
    return textRect;
}

您看到的并不是图标不透明——文本只是被绘制在它上面,因为文本字段并不“知道”图标在那里。

您还可以查看 rightView 属性和相关的 -rightViewRectForBounds: 方法,但如果您希望文本字段自动显示和隐藏附件视图,这些方法最有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2016-08-12
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多