「Swift」NSAttributedStringでUITextFieldのPlaceholderを設定するサンプル

2022年2月28日

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
textField.attributedPlaceholder = NSAttributedString(string: "placeholderに表示する文言", attributes: 属性定義)
textField.attributedPlaceholder = NSAttributedString(string: "placeholderに表示する文言", attributes: 属性定義)
textField.attributedPlaceholder = NSAttributedString(string: "placeholderに表示する文言", attributes: 属性定義)

NSAttributedStringを使ってテキストフィールドのplaceholderの色や、サイズを変更します。
書式
let 変数名: [NSAttributedString.Key : Any] = [
.font : UIFont.boldSystemFont(ofSize: 18.0), // 文字サイズ、太さ
.foregroundColor : UIColor.green // 文字色
]

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
    // フォントサイズ:18、太さ:bold 色:green
let attr: [NSAttributedString.Key : Any] = [
.font: UIFont.boldSystemFont(ofSize: 18.0),
.foregroundColor : UIColor.green
]
textField.attributedPlaceholder = NSAttributedString(string: "名前を追加", attributes: attr)
}
}
class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad()     // フォントサイズ:18、太さ:bold 色:green let attr: [NSAttributedString.Key : Any] = [ .font: UIFont.boldSystemFont(ofSize: 18.0), .foregroundColor : UIColor.green ] textField.attributedPlaceholder = NSAttributedString(string: "名前を追加", attributes: attr) } }
class ViewController: UIViewController, UITableViewDataSource {

  @IBOutlet weak var textField: UITextField!

  override func viewDidLoad() {
    super.viewDidLoad()
  
     // フォントサイズ:18、太さ:bold  色:green
    let attr: [NSAttributedString.Key : Any] = [
      .font: UIFont.boldSystemFont(ofSize: 18.0), 
      .foregroundColor : UIColor.green 
    ]

    textField.attributedPlaceholder = NSAttributedString(string: "名前を追加", attributes: attr)
  }
}

結果
テキストフィールドのplaceholderに「名前を追加」が表示され、太字で色が緑になります。

Swift

Posted by arkgame