web-dev-qa-db-ja.com

テキストフィールドのプレースホルダーを中央揃えにします

私はこの質問が何度も聞かれることを知っていますが、drawinrectは非推奨であり、iOS 8でこれが必要です。テキストフィールドがあり、中央にプレースホルダーが必要で、残りのテストは左に揃える必要があります。助けてください。

9
ashForIos

IBOutletを作成してtextFieldに接続します。で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;
}
7
Mayank Jain

受け入れられた答え方法物事を過度に複雑にします...

段落スタイルと組み合わせてattributedPlaceholderを使用することにより、プレースホルダーをUITextFieldの中央に配置できます。

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

@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;
6
aug2uag

Clay Ellisの回答に基づく

詳細

  • 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)
    }
}

結果

enter image description here

2

@ClayEllisによる答えSwift 5

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