26

自動レイアウトを使用して、UIViewをスーパービューの中央にプログラムで設定するにはどうすればよいですか?

UIButton* viewObj = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[viewObj setTranslatesAutoresizingMaskIntoConstraints:NO];
[viewObj setBackgroundColor:[UIColor greenColor]];
[self.view addSubview:viewObj];

NSLayoutConstraint* cn = [NSLayoutConstraint constraintWithItem:viewObj
                                                      attribute:NSLayoutAttributeCenterX
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterX 
                                                     multiplier:1.0
                                                       constant:0];
[self.view addConstraint:cn];
cn = [NSLayoutConstraint constraintWithItem:viewObj 
                                  attribute:NSLayoutAttributeCenterY
                                  relatedBy:NSLayoutRelationEqual 
                                     toItem:self.view
                                  attribute:NSLayoutAttributeCenterY
                                 multiplier:1.0
                                   constant:0];
[self.view addConstraint:cn];

上記のコードはUIButtonで機能しますが、最初の行をUIViewで機能するものに置き換えるのに問題があります。

私はもう試した

UIView* viewObj = [UIView alloc] initWithFrame:CGRectZero];

ただし、ビューはシミュレーターに表示されません。

助言がありますか?

ありがとう!

4

2 に答える 2

21

自動レイアウトを使用するコンテキストでこの質問をしたので、ここでの問題は、UIButtonが幅と高さに関する情報を自動レイアウトに提供する固有のサイズ(intensitiveContentSizeメソッドを介して通信される)を持っていることですが、UIViewは通常そうではありません。したがって、幅と高さに関連する制約をさらに追加する必要があります。

UIViewを設定されたサイズ(たとえば、200x200)にする場合は、次の行を追加できます。

cn = [NSLayoutConstraint constraintWithItem:viewObj 
                                  attribute:NSLayoutAttributeHeight
                                  relatedBy:NSLayoutRelationEqual 
                                     toItem:nil
                                  attribute:NSLayoutAttributeNotAnAttribute 
                                 multiplier:1
                                   constant:200];
[viewObj addConstraint:cn];

cn = [NSLayoutConstraint constraintWithItem:viewObj
                                  attribute:NSLayoutAttributeWidth
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:nil
                                  attribute:NSLayoutAttributeNotAnAttribute 
                                 multiplier:1 
                                   constant:200];
[viewObj addConstraint: cn];

toItem:引数はnilであり、2番目の属性はであることに注意してください。これはNSLayoutAttributeNotAnAttribute、他のものとの相対的な幅と高さを指定していないためです。サブビューの高さと幅をスーパービュー(たとえば、0.5)に対して相対的にしたい場合は、次のようにすることができます。

cn = [NSLayoutConstraint constraintWithItem:viewObj
                                  attribute:NSLayoutAttributeHeight
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:self.view
                                  attribute:NSLayoutAttributeHeight 
                                 multiplier:0.5 
                                   constant:0];
[self.view addConstraint:cn];
cn = [NSLayoutConstraint constraintWithItem:viewObj
                                  attribute:NSLayoutAttributeWidth
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:self.view
                                  attribute:NSLayoutAttributeWidth
                                 multiplier:0.5
                                   constant:0];
[self.view addConstraint: cn];
于 2012-12-23T15:02:16.603 に答える
7

UIButton、、UIImageViewおよびコンテンツのプロパティに応じてサイズを自動的に設定できますUIlabelUITextFieldaの幅と高さは、含まれる可能性UIImageViewのあるものによって設定されUIImageます。aのサイズは、UILabelそのテキストによって異なります。aの幅と高さはUIButton、タイトルとその画像によって定義されます(詳細については、[固有のコンテンツサイズ]を参照してください)。

したがって、自動レイアウトを使用して、、、、または内部を中央に配置する場合UIButton、ほとんどの場合、幅と高さの制約を作成する必要はありません。それらに水平および垂直の制約を設定する必要があります。UILabelUITextFieldUIImageViewUIView

ただし、自動レイアウトでUIViewは、サブビューを持たないaは、任意の幅と高さの制約を指定しない限り、サイズの設定に何も依存できません。そして、あなたのニーズに応じて、3つの異なる方法でこれを解決することができます。


純粋な自動レイアウトスタイル

ここでは、UIView自動レイアウト制約として直接幅と高さを設定します。

override func viewDidLoad() {
    super.viewDidLoad()

    let newView = UIView()
    newView.backgroundColor = .redColor()
    newView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(newView)

    // Auto layout code using anchors (iOS9+)
    let horizontalConstraint = newView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
    let verticalConstraint = newView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor)
    let widthConstraint = newView.widthAnchor.constraintEqualToAnchor(nil, constant: 100)
    let heightConstraint = newView.heightAnchor.constraintEqualToAnchor(nil, constant: 100)
    NSLayoutConstraint.activateConstraints([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}

自動サイズ変更マスクスタイル

ここではUIView、幅と高さで初期化し、中心とスーパービューの中心を等しくして、自動サイズ変更マスクを作成します。次に、UIKitにこれらの自動サイズ変更マスクを自動レイアウト制約に変換するように依頼します。

override func viewDidLoad() {
    super.viewDidLoad()
    
    let newView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
    newView.backgroundColor = .redColor()
    
    newView.center = CGPointMake(view.bounds.midX, view.bounds.midY)
    newView.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleTopMargin, .FlexibleBottomMargin]

    newView.translatesAutoresizingMaskIntoConstraints = true // default is true
    view.addSubview(newView)
}

サブクラススタイル

ここでは、のサブクラスを作成し、そのメソッド(宣言UIView)をオーバーライドして、目的のサイズを返すようにします。intrinsicContentSize()

import UIKit

class CustomView: UIView {
    override func intrinsicContentSize() -> CGSize {
        return CGSize(width: 100, height: 100)
    }
}

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let newView = CustomView()
        newView.backgroundColor = .redColor()
        newView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(newView)
        
        let horizontalConstraint = NSLayoutConstraint(item: newView,
            attribute: .CenterX,
            relatedBy: .Equal,
            toItem: view,
            attribute: .CenterX,
            multiplier: 1,
            constant: 0)
        view.addConstraint(horizontalConstraint)
        let verticalConstraint = NSLayoutConstraint(item: newView,
            attribute: .CenterY,
            relatedBy: .Equal,
            toItem: view,
            attribute: .CenterY,
            multiplier: 1,
            constant: 0)
        view.addConstraint(verticalConstraint)
    }
    
}
于 2015-12-27T18:01:36.777 に答える