在文本字段中居中对齐占位符

Posted

技术标签:

【中文标题】在文本字段中居中对齐占位符【英文标题】:Center align placeholder in textfield 【发布时间】:2015-04-08 21:28:25 【问题描述】:

我知道这个问题被问过很多次,但由于不推荐使用 drawinrect,我在 ios 8 中需要这个。因为我有一个文本字段,我需要居中对齐的占位符,其余的测试左对齐。请帮帮我。

【问题讨论】:

【参考方案1】:

您可以使用带有对齐设置为.center 的段落样式的attributedPlaceholder 来居中占位符:

let centeredParagraphStyle = NSMutableParagraphStyle()
centeredParagraphStyle.alignment = .center
textField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder", 
    attributes: [.paragraphStyle: centeredParagraphStyle]
)

【讨论】:

【参考方案2】:

创建 IBOutlet 并将其连接到您的文本字段。在 YourViewController.m

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

在您的 viewDidLoad

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

编写此委托方法。每次文本字段中的文本更改时都会调用此方法。

- (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;

【讨论】:

请参阅下面的我的答案,了解 4 行解决方案减去涉及代表的需要。此外,@ashForIos,您应该更改已接受的答案,以帮助社区找到更好的解决方案。【参考方案3】:

@Clay Ellis 的答案是正确的,这是针对 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;

【讨论】:

【参考方案4】:

基于克莱·埃利斯的回答

详情

Xcode 版本 10.2.1 (10E1001),Swift 5

解决方案 1

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

解决方案 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)
    

解决方案2的使用

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

完整样本

别忘了在此处添加解决方案代码

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)
    

结果

【讨论】:

不起作用.. 在 Xcode 版本 10.3 (10G8) ios 12.1、Swift 4.2 :: let paragraphStyleCenter = NSMutableParagraphStyle() paraStyleCenter.alignment = .center textField.attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes: [.font: UIFont(name: FONT_MEDIUM, size: 14) ?? UIFont.boldSystemFont(ofSize: 14), paragraphStyle: paragraphStyleCenter]) @A.Trejo 试试这个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);【参考方案5】:

@Clay Ellis 在 Swift 5 中的回答

let centeredParagraphStyle = NSMutableParagraphStyle()
    centeredParagraphStyle.alignment = .center
    let attributedPlaceholder = NSAttributedString(string: "Placeholder", attributes: [NSAttributedString.Key.paragraphStyle: centeredParagraphStyle])
    textField.attributedPlaceholder = attributedPlaceholder

【讨论】:

以上是关于在文本字段中居中对齐占位符的主要内容,如果未能解决你的问题,请参考以下文章

在文本字段 HTML 内对齐占位符

如何在 React Material UI TextField 中居中占位符和文本

iOS7 搜索栏占位符文本对齐问题

文本对齐:右;仅用于占位符?

android中的中心对齐占位符问题

输入占位符在 Firefox 中未垂直对齐