【问题标题】:How to place an icon / image inside an UITextFIeld just next to the last letter of the text?如何在文本最后一个字母旁边的 UITextFIeld 中放置图标/图像?
【发布时间】:2018-05-27 02:58:45
【问题描述】:

我有一个文本字段,其中的值由我从服务器获取的字符串填充。我想在我的文本字段中设置一个图标,只是为了向用户显示该文本字段实际上不是标签,但可以对其进行编辑。我经历了其他问题,但只找到了在 leftViewMode 或 RightViewMode 上设置图标的答案。我怎样才能实现它?

    _titleLabel.delegate = self;
    UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"edit_Canvas_name"]];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    [_titleLabel setRightViewMode:UITextFieldViewModeAlways];
    [_titleLabel setRightView:imgView];

我希望图像在“触摸 - 绘图”中的 g 之后。

【问题讨论】:

    标签: ios objective-c xcode uiimageview uitextfield


    【解决方案1】:

    编写一个返回 UITextField 文本宽度的方法。然后将图像放在后面。方法会是这样的,

    - (float)textWidthOf:(UITextField *)textfield {
        CGSize textSize = [textfield.text sizeWithAttributes:@{NSFontAttributeName : textfield.font}];
        return textSize.width;
    }
    

    【讨论】:

      【解决方案2】:

      在文本字段中添加按钮并根据该设置框架或约束,以便您可以在“触摸 - 绘图”中获得“g”旁边的按钮。

      UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
      
      [btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
      
      btn.frame = CGRectMake(self.yourTextField.bounds.size.width - 50, 5, 25, 25);
      
      [btn setBackgroundImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal];
      
      [self.yourTextField addSubview:btn];
      

      【讨论】:

      • 请描述你给他的约束是什么以及你是如何设置的,以便人们理解。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2016-12-22
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多