23
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【AutoLayout】UILabelの幅を文字列の長さに合わせて可変にする方法

Posted at

デモ

autoWidth.gif

手順

UILabelを設置したらAutoLayoutでwidthを適当な値で設定します。
01.png

次に先程設定した制約を編集していきます。
Constantという項目がありますので「≧」を選択してください。
これで右側の数字よりwidthが大きくなった場合、自動的に幅を文字列の長さに合わせる設定になります。
02.png

デモのコード

ViewController.swift
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        label.text = textField.text
        return true
    }
}
23
28
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
28

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?