2017-08-21 6 views
1

UI Labelを追加していますが、プログラム的なUIコードを試しています。NSLayoutを使用してUILabelのX値とY値を設定する

let titleLabel: UILabel = { 
    let lb = UILabel() 
    lb.translatesAutoresizingMaskIntoConstraints = false 
    lb.textAlignment = .center 
    lb.numberOfLines = 1 
    lb.textColor = UIColor.black 
    lb.font=UIFont.systemFont(ofSize: 22) 
    lb.backgroundColor = UIColor.white 
    return lb 

してから、このコードを使用して制約を追加しました::私はこのコードを使用して、私のラベルを設定し、私は後に、この関数を呼び出す

func setupTitleLabel() { 


    titleLabel.translatesAutoresizingMaskIntoConstraints = false 
    titleLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true 
    titleLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true 
    titleLabel.centerXAnchor.constraint(equalTo: titleLabel.superview!.centerXAnchor).isActive = true 
    titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true 
} 

を。しかし、私はXとYの値に変更する方法がわかりません。現在、XとYの両方のページの中央に設定されていますが、どのように上に移動しますか?私はケースラベルがcenterXとcenterYであることであることを理解し、あなたがそのようにスーパーlater.Ifのトップになりたい何

+0

は、 'titleLabel.superview.centerXAnchor'と' titleLabel.superview!centerYAnchor'の代わりに、この2つの 'titleLabel.superview!.adingAnchor'、' titleLabel.superview!.topAnchor'を使用します。 –

答えて

1

、あなたは間違ってtitleLabel.superview!.centerYAnchorを使用しているあなたは、ラベルスーパーのトップにあなたのラベルを固定が必要な場合は、代わりにtitleLabel.superview!.topAnchorを使用する必要がある

この

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true 
を置き換えます

これによる

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.topAnchor).isActive = true 
+0

ラベルがどこにあり、lbl.text = "string"がテキストを表示していないかを確認するためにテキストを追加しようとしています:/ – user8480321

+0

あなたのUILabelがあなたの望みのビューに追加されたことを確かめていますか? 'self.view.addSubView(self.titleLabel)'どこにでもありません@ user8480321 –

+0

あなたは正しいです、それは間違ったビューでした – user8480321

0

は、私はあなたが使用することができると思うvar centerYAnchor: NSLayoutConstraint?

centerYAnchor = titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor) 
centerYAnchor.isActive = true 

後でラベルを変更する場合は、centerYAnchor.isActive = falseと設定し、ラベルのtopAnchorを設定します。私は私のコメントで述べたよう

titleLabel.topAnchor.constraint(equalTo: titleLabel.superview!.topAnchor).isActive = true 
+0

私は単にページ。私はページの先端に何かY値を設定しようとしていますが、それは動作していないようです。あなたの方法では、それは真ん中からY値がわずかに増加するだけです – user8480321

+0

私はcenterXAnchor、heightAnchor、widthAnchorとtopAnchorを考えると、4つのアンカーはあなたが望む位置にラベルを作るのに十分です。 –

関連する問題