I need to implement the concept of dropdown
in Xcode.
For
emailTextField.leftViewMode = .alway
let emailImgContainer = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 25))
let emailImg = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
emailImg.image = UIImage(named: "SomeIMG")
emailImgContainer.addSubview(emailImg)
emailTextField.leftView = emailImgContainer
enter image description here
Step 1: Add this class to your project and add it to your textFiled's class in identity inspector,
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
}
}
Step 2: Set text insets and left image from interface builder.
Step 3: Enjoy.
hey mate you want dropdown view then see this custom dropdown view ..
and for this requirement use this code
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];
and set your textfield border style none..
To add proper margins / paddings between image and textfield, try this below code. Expanding on @King-Wizard's answer.
Here the height of my TextField is 44 Check the attached image for reference.
Swift Version:
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
In Swift:
textField.leftViewMode = UITextFieldViewMode.Always
textField.leftView = UIImageView(image: UIImage(named: "imageName"))
You can put the UIImageView
to the left of your UITextField
.
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(96, 40, 130, 20)];
[textField setLeftViewMode:UITextFieldViewModeAlways];
textField.leftView= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"searchIccon.png"]];