chineseGirl
chineseGirl

Reputation: 179

How to change textfield font size programmatically?

I have a button that creates a text field, I also have a button to change the text field's font. I created 3 button with different titles: 17,20,36. I want the functions of that button to change the font size of the text field, how can I do this?

Upvotes: 9

Views: 29593

Answers (6)

Amit Baderia
Amit Baderia

Reputation: 4882

Swift 4:

textField1.font = UIFont(name: "Avenir", size: 22)

Upvotes: 1

Mohamed AbdelraZek
Mohamed AbdelraZek

Reputation: 2799

you can use NSAttributedString to add properties to TextField

let textAttributes: [NSAttributedString.Key: Any] = [
        NSAttributedString.Key.strokeColor: /* TODO: fill in appropriate UIColor */,
        NSAttributedString.Key.foregroundColor: /* TODO: fill in appropriate UIColor */,
        NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
        NSAttributedString.Key.strokeWidth:  /* TODO: fill in appropriate Float */
    ]

yourTextField.defaultTextAttributes = textAttributes 

Upvotes: 1

Ortensia C.
Ortensia C.

Reputation: 4716

Swift 4 is this:

yourTextField.font =  UIFont.init(name: (Montserrat.bold.rawValue), size: 18.0)

Instead Monserrat use your font

Upvotes: 8

inf1783
inf1783

Reputation: 964

Swift 3 Version of accepted answer:

let yourTextField = UITextField()
let customFont:UIFont = UIFont.init(name: (textField.font?.fontName)!, size: 14.0)!
font = customFont
yourTextField.font = customFont

Upvotes: 3

damithH
damithH

Reputation: 5178

yes you can do it.

but you have to change the textField's frame also(to show the full(height) text)

[tFild_1 setFont:[UIFont fontWithName:@"Helvetica Neue" size:17]];

instead of "Helvetica Neue" use your font name.

thanx,

Upvotes: 1

monjer
monjer

Reputation: 2929

If you want to simply change your textfield's font size , and not change it's font style at the same time , code below may be work : `

UITextField *yourTextField = [[UITextField alloc]init];
CGFloat yourSelectedFontSize = 14.0 ;
UIFont *yourNewSameStyleFont = [yourTextField.font fontWithSize:yourSelectedFontSize];
yourTextField.font = yourNewSameStyleFont ;

One thing you have to note is that : when you change your textfield's font size , you should always pay attention to your textfield view's height , keep your textfiled's height taller than your font height !

You can have a try !

Upvotes: 13

Related Questions