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.
Center align placeholder in textfield
Asked Answered
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;
}
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
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]
)
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
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;
}
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
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;
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
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 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
© 2022 - 2024 — McMap. All rights reserved.