Center align placeholder in textfield
Asked Answered
A

5

14

I know this question been asked many times but as drawinrect deprecated and I need this in ios 8.As I have a textfield and I need the placeholder in center align and rest of the test left align.Please help me out.

Acatalectic answered 9/2, 2015 at 7:24 Comment(0)
N
9

Create and connect IBOutlet to your textField. In YourViewController.m

@interface YourViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txt;

In your viewDidLoad

self.txt.delegate=self;
self.txt.textAlignment=NSTextAlignmentCenter;

Write this delegate method..this method calls everytime when text in text field changes.

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {

    NSRange textFieldRange = NSMakeRange(0, [self.txt.text length]);
    // Check If textField is empty. If empty align your text field to center, so that placeholder text will show center aligned
    if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
    self.txt.textAlignment=NSTextAlignmentCenter;
    }
    else //else align textfield to left. 
    {
        self.txt.textAlignment=NSTextAlignmentLeft;
    }
    return YES;
}
Nosology answered 9/2, 2015 at 7:27 Comment(1)
See my answer below for a 4 line solution minus the need to involve a delegate. Also, @ashForIos, you should change the accepted answer to help point the community towards a better solution.Patently
P
31

You can center the placeholder by using an attributedPlaceholder with a paragraph style whose alignment is set to .center:

let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
textField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder", 
    attributes: [.paragraphStyle: centeredParagraphStyle]
)
Patently answered 26/8, 2016 at 1:11 Comment(1)
this answer doesn't work for me, as soon as I set alignment for textfield, place holder uses that alignment and forgets about attributed thing.Sirotek
N
9

Create and connect IBOutlet to your textField. In YourViewController.m

@interface YourViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txt;

In your viewDidLoad

self.txt.delegate=self;
self.txt.textAlignment=NSTextAlignmentCenter;

Write this delegate method..this method calls everytime when text in text field changes.

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {

    NSRange textFieldRange = NSMakeRange(0, [self.txt.text length]);
    // Check If textField is empty. If empty align your text field to center, so that placeholder text will show center aligned
    if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
    self.txt.textAlignment=NSTextAlignmentCenter;
    }
    else //else align textfield to left. 
    {
        self.txt.textAlignment=NSTextAlignmentLeft;
    }
    return YES;
}
Nosology answered 9/2, 2015 at 7:27 Comment(1)
See my answer below for a 4 line solution minus the need to involve a delegate. Also, @ashForIos, you should change the accepted answer to help point the community towards a better solution.Patently
I
7

The answer by @Clay Ellis is correct, here it is for Objective-C:

UITextField* field = [[UITextField alloc] initWithFrame: fieldRect];
NSTextAlignment alignment = NSTextAlignmentCenter;
NSMutableParagraphStyle* alignmentSetting = [[NSMutableParagraphStyle alloc] init];
alignmentSetting.alignment = alignment;
NSDictionary *attributes = @{NSParagraphStyleAttributeName : alignmentSetting};
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeholder attributes: attributes];
field.attributedPlaceholder = str;
Immutable answered 19/12, 2016 at 1:55 Comment(0)
T
4

based on Clay Ellis answer

Details

  • Xcode Version 10.2.1 (10E1001), Swift 5

Solution 1

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
textField.attributedText = NSAttributedString(string: placeholder, attributes: [.paragraphStyle: paragraphStyle])

Solution 2

import Foundation

extension String {
    func toAttributed(alignment: NSTextAlignment) -> NSAttributedString {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
        return toAttributed(attributes: [.paragraphStyle: paragraphStyle])
    }

    func toAttributed(attributes: [NSAttributedString.Key : Any]? = nil) -> NSAttributedString {
        return NSAttributedString(string: self, attributes: attributes)
    }
}

Usage of the solution 2

// Way 1
textField.attributedPlaceholder = text.attributedString(alignment: .center)
// Way 2
textField.attributedPlaceholder = "title".attributedString(alignment: .center)

Full sample

Do not forget to add the solution code here

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = UITextField()
        textField.borderStyle = .roundedRect
        view.addSubview(textField)
        //textField.attributedPlaceholder = getAttributedString1()
        textField.attributedPlaceholder = getAttributedString2()
        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24).isActive = true
        textField.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 16).isActive = true
        view.safeAreaLayoutGuide.rightAnchor.constraint(equalTo: textField.rightAnchor, constant: 16).isActive = true
    }

    private func getAttributedString1() -> NSAttributedString {
        return "placeholder".toAttributed(alignment: .center)
    }

    private func getAttributedString2() -> NSAttributedString {
        var attributes = [NSAttributedString.Key: Any]()
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
        attributes[.paragraphStyle] = paragraphStyle
        attributes[.font] = UIFont.systemFont(ofSize: 12, weight: .bold)
        attributes[.foregroundColor] = UIColor.black.withAlphaComponent(0.5)
        attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue
        attributes[.underlineColor] = UIColor.red
        return "placeholder".toAttributed(attributes: attributes)
    }
}

Results

enter image description here

Toddle answered 7/11, 2017 at 10:3 Comment(2)
Does not work.. in Xcode Version 10.3 (10G8) ios 12.1, Swift 4.2 :: let paragraphStyleCenter = NSMutableParagraphStyle() paragraphStyleCenter.alignment = .center textField.attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes: [.font: UIFont(name: FONT_MEDIUM, size: 14) ?? UIFont.boldSystemFont(ofSize: 14), paragraphStyle: paragraphStyleCenter])Anterior
@A.Trejo try this var attributes = [NSAttributedString.Key: Any](); let paragraphStyle = NSMutableParagraphStyle(); paragraphStyle.alignment = .center; attributes[.paragraphStyle] = paragraphStyle; attributes[.font] = UIFont.boldSystemFont(ofSize: 14); textField.attributedPlaceholder = "placeholder".toAttributed(attributes: attributes);Toddle
W
4

The answer by @Clay Ellis in Swift 5

let centeredParagraphStyle = NSMutableParagraphStyle()
    centeredParagraphStyle.alignment = .center
    let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
    textField.attributedPlaceholder = attributedPlaceholder
Warty answered 12/6, 2019 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.