在Xcode中添加图像到UITextField?
我需要在Xcode中实现dropdown
的概念。
为此,我正在使用UIPickerview
。
这个pickerView当一个文本域被点击时(在textFieldDidBeginEditing:)事件中加载。
题:
有没有办法,我可以添加一个图像到TextField
?
图像就像一个箭头标记,通过这个箭头标记,用户可以理解当点击textfield
时出现dropdown
我该如何做?
UITextField有一个rightView
属性,如果你有像这样的图像 – 那么你可以轻松地将ImageView对象设置为rightView:
UITextField *myTextField = [[UITextField alloc] init]; myTextField.rightViewMode = UITextFieldViewModeAlways; myTextField.rightView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"downArrow.png"]];
你可以把UIImageView
放在你的UITextField
的左边。
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(96, 40, 130, 20)]; [textField setLeftViewMode:UITextFieldViewModeAlways]; textField.leftView= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchIccon.png"]];
在Swift中:
textField.leftViewMode = UITextFieldViewMode.Always textField.leftView = UIImageView(image: UIImage(named: "imageName"))
Swift 3.0
txtField.rightViewMode = .always txtField.rightView = UIImageView(image: UIImage(named: "selectdrop"))
要在图像和文本字段之间添加适当的边距/填充,请尝试下面的代码。 扩展@ King-Wizard的答案。
这里我的TextField的高度是44检查附加的图像作为参考。
Swift版本:
emailTF.leftViewMode = .Always let emailImgContainer = UIView(frame: CGRectMake(emailTF.frame.origin.x, emailTF.frame.origin.y, 40.0, 30.0)) let emailImView = UIImageView(frame: CGRectMake(0, 0, 25.0, 25.0)) emailImView.image = UIImage(named: "image1") emailImView.center = emailImgContainer.center emailImgContainer.addSubview(emailImView) emailTF.leftView = emailImgContainer
嘿伙伴你想下拉查看,然后看到这个自定义下拉查看..
- http://code.google.com/p/dropdowndemo/downloads/list
- http://ameyashetti.wordpress.com/2010/09/26/drop-down-demo/
并为此要求使用此代码
UITextField *txtstate =[[UITextField alloc]init]; [txtstate setFrame:CGRectMake(10, 30,170, 30)]; txtstate.delegate=self; txtstate.text=@"Fruits"; txtstate.borderStyle = UITextBorderStyleLine; txtstate.background = [UIImage imageNamed:@"dropdownbtn.png"]; [txtstate setAutocorrectionType:UITextAutocorrectionTypeNo]; [self.view addSubview:txtstate];
并设置您的文本框边框样式无..
UITextField具有以下属性:
@property(nonatomic, retain) UIImage *background
例:
UITextField *myTextField = [[UITextField alloc] init]; myTextField.background = [UIImage imageNamed:@"myImage.png"];
第1步:将这个类添加到您的项目中,并将其添加到您的textFiled类的身份检查器中,
class MyCustomTextField: UITextField { @IBInspectable var inset: CGFloat = 0 @IBInspectable var leftImage: String = String(){ didSet{ leftViewMode = UITextFieldViewMode.Always leftView = UIImageView(image: UIImage(named: leftImage)) } } override func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, inset, inset) } override func editingRectForBounds(bounds: CGRect) -> CGRect { return textRectForBounds(bounds) } override func leftViewRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(CGRectMake(0, 2, 40, 40), 10, 10) //Change frame according to your needs } }
第2步:设置文本插入和左侧的图像从界面生成器。
第3步:享受。