[英]How to center the text in a UITextField although there exists a leftView?
[英]How to set the leftview location on UITextfield to be close to the placehoder text
我正在使用UITextfield作为搜索字段,以允许用户过滤内容。 当用户打开UI时,UITextField将在文本字段的中心显示一个占位符消息“搜索”。 我想在占位符文本之前添加一个leftview图标(请参见下面的代码)。 左行图标将显示在文本字段的最左侧。 我想将其放在文本之前。 如何找到合适的位置?
searchText.placeholder = "Search"
searchText.leftView = UIImageView(image: UIImage(named: "cion_03.png"))
searchText.leftView?.contentMode = .ScaleAspectFit
searchText.leftViewMode = .Always
您忘记设置框架了。 尝试为您的图片设置适当的x
位置。
let icon = UIImageView(image: UIImage(named: "cion_03"))
icon.frame = CGRectMake(0.0, 0.0, icon.image.size.width+10.0, icon.image.size.height);
icon.contentMode = UIViewContentMode.Center
self.textField.leftView = icon;
self.textField.leftViewMode = UITextFieldViewMode.Always
对于这种定制级别,最好的选择是UITextField
。 您将能够修改占位符文本的框架,以修改其位置。
您应该覆盖placeholderRectForBounds:
更改后,您可能会发现需要覆盖textRectForBounds:
来匹配占位符文本位置。
我已经看到这种方法可以成功使用,以适应某些字体。
我花了一天的时间尝试使用UITextField子类来执行此操作。 它可以正常工作,但是在编辑时我还需要将文本对齐方式从居中更改为左对齐。 我最终通过将图像视图限制在文本字段的前面来解决了这个问题,并且效果很好。 我什至能够对它们进行来回动画。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.