Mohammed Janish
Mohammed Janish

Reputation: 207

How to add a custom image for the textfield in UIsearchbar iOS swift

I am trying to create a custom search bar. I want to add a custom image for the textfield in the search bar. I set the searchbarstyle minimal. I used the following code to change the background image. it doesn't fit well. This outlets are added programmatically

let srchtextfld: UITextField = srchbr.valueForKey("searchField") as! UITextField

    srchtextfld.layer.backgroundColor = UIColor(patternImage: UIImage(named: "Rounded Rectangle 1 copy 3.png")!).CGColor

I am Getting the below image

enter image description here

I want to add this type of image as its background

enter image description here

Any help is appreciated

Upvotes: 0

Views: 1275

Answers (1)

Imran
Imran

Reputation: 2941

If you want to set the background image then property is background not backgroundColor see docs . So you do like this

srchtextfld.background  = UIImage(named: "Rounded Rectangle 1 copy 3.png")!

Also remember

When set, the image referred to by this property replaces the standard appearance controlled by the borderStyle property. Background images are drawn in the border rectangle portion of the text field. Images you use for the text field’s background should be able to stretch to fit.

Plus

UITextBorderStyleRoundedRect, custom background images are ignored.

Upvotes: 1

Related Questions