Whirlwind
Whirlwind

Reputation: 13675

Having textfield background transparent, but placeholder text opaque

Is it possible to have a textfield's placeholder text opaque while its background is set to be transparent, eg. if I choose some background color, and set alpha to some value, like this: enter image description here

the placeholder text becomes transparent as well. But I want it opaque. So, is this achievable, preferably using storyboard ? Or at least through the code.

If it is unclear what I am trying to achieve, just let me know , and I'll post an image with an example.

Upvotes: 1

Views: 2008

Answers (3)

Gaspar
Gaspar

Reputation: 52

You can set the UITextView.background = .clear

I'm providing a little more code so it'll be easier to setup it programmatically, this is a ready-to-use sample.

private lazy var textField: UITextView = {
    let textField = UITextView()
    textField.translatesAutoresizingMaskIntoConstraints = false
    textField.font = UIFont.systemFont(ofSize: 14)
    textField.isEditable = false
    textField.textAlignment = .center
    textField.isScrollEnabled = false
    textField.backgroundColor = .clear // this is the line that answer you question
    textField.text = """
        People with these symptoms may have COVID-19:
        Fever of chills, cough, shortness of breath or
        difficulty breathing, fatigue, muscle or body aches,
        headache, new loss of taste and smell, sore throat,
        congestion or runny nose, nausea or vomiting,
        diarrhea
        """
    
    return textField
}()

Just remember to set the constraints and add the subview into your superview .addSubview(TextField)

Upvotes: 0

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

In Swift you can obtain the placeholder element with:

let placeHolder = textField.value(forKey: "placeholderLabel") as! UILabel
placeHolder.textColor = .blue
placeHolder.isOpaque = true

and make all customizations you prefeer..

Upvotes: 1

mikeytdan
mikeytdan

Reputation: 254

You can set the color's transparency instead of the UITextField's alpha. Open the color drop down and select "Other". A color picker will open up. At the bottom of the color picker you can change the opacity.

Upvotes: 1

Related Questions