Programing

UIView의 서브 뷰를 중앙에 배치하는 방법

crosscheck 2020. 7. 16. 08:15
반응형

UIView의 서브 뷰를 중앙에 배치하는 방법


나는 UIView내부에 UIViewm 이 있고 내부가 UIView너비와 높이의 크기를 조정할 필요없이 항상 외부 내부의 가운데에 오기 원합니다 .

스트럿과 스프링을 크기 조정을 설정하지 않고 상단 / 왼쪽 / 오른쪽 / 하단에 놓았습니다. 그러나 여전히 중심에 있지 않습니다. 어떤 생각?


목표 -C

yourSubView.center = CGPointMake(yourView.frame.size.width  / 2, 
                                 yourView.frame.size.height / 2);

빠른

yourSubView.center = CGPoint(x: yourView.frame.size.width  / 2,
                             y: yourView.frame.size.height / 2)

이 작업을 수행하면 항상 작동합니다.

child.center = [parent convertPoint:parent.center fromView:parent.superview];

그리고 스위프트의 경우 :

child.center = parent.convert(parent.center, from:parent.superview)

시작하기 전에 원점 CGPoint이 뷰의 왼쪽 위 모서리임을 상기시켜 봅시다 . 견해와 부모에 관해 이해해야 할 중요한 것.

이 간단한 코드,보기에 검은 사각형을 추가하는 뷰 컨트롤러를 살펴 보겠습니다.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        createDummyView()
        super.view.backgroundColor = UIColor.cyanColor();
    }

    func createDummyView(){
        var subView = UIView(frame: CGRect(x: 15, y: 50, width: 50 , height: 50));
        super.view.addSubview(subView);
        view.backgroundColor = UIColor.blackColor()
    }

}

검은 색 사각형 원점과 중심이 부모와 같은 좌표에 맞습니다.

여기에 이미지 설명을 입력하십시오

이제 subView에 다른 SubSubView를 추가하고 subSubview와 동일한 원점을 subView에 제공하려고 시도하지만 subSubView를 subView의 하위보기로 만듭니다.

이 코드를 추가하겠습니다 :

var subSubView = UIView();
subSubView.frame.origin = subView.frame.origin;
subSubView.frame.size = CGSizeMake(20, 20);
subSubView.backgroundColor = UIColor.purpleColor()
subView.addSubview(subSubView)

그리고 이것은 결과입니다 :

여기에 이미지 설명을 입력하십시오

이 줄 때문에 :

subSubView.frame.origin = subView.frame.origin;

자주색 직사각형의 원점이 부모 (검은 색 직사각형)와 같을 것으로 예상되지만 그 아래에 있습니다. 그 이유는 무엇입니까? 다른 뷰에 뷰를 추가 할 때 서브 뷰 프레임 "world"는 이제 상위 BOUND RECTANGLE입니다. 메인 화면에서 원점이 뷰인 경우 뷰의 모든 뷰에 대해 뷰 (15,15)가됩니다. 왼쪽 상단은 (0,0)입니다

그렇기 때문에 subViews의 "세계"인 바운드 사각형으로 부모를 항상 참조 해야하는 이유는 다음과 같습니다.

subSubView.frame.origin = subView.bounds.origin;

그리고 마술을보십시오, subSubview는 이제 정확히 부모 원점에 있습니다 :

여기에 이미지 설명을 입력하십시오

"좋아요. 부모님의 견해로만 내 견해를 집중하고 싶었습니다. 큰 문제는 무엇입니까?" 글쎄요, 큰 문제는 아닙니다. 당신은 이것을 수행함으로써 부모 중심점을 프레임에서 부모의 경계 센터로 "번역"하면됩니다 :

subSubView.center = subView.convertPoint(subView.center, fromView: subSubView);

당신은 실제로 그에게 "부모님의 견해를 가져 가서 subSubView 세계로 변환하십시오"라고 말하고 있습니다.

그리고 당신은이 결과를 얻을 것이다 :

여기에 이미지 설명을 입력하십시오


나는 사용할 것이다 :

self.childView.center = CGPointMake(CGRectGetMidX(self.parentView.bounds),
                                    CGRectGetMidY(self.parentView.bounds));

CGRect옵션 을 사용하고 싶습니다 ...

스위프트 3 :

self.childView.center = CGPoint(x: self.parentView.bounds.midX,
                                        y: self.parentView.bounds.midY);

1. 자동 레이아웃이 활성화 된 경우 :

  • 힌트 : 자동 레이아웃이있는 다른 뷰의 뷰를 중앙에 배치하기 위해 하나 이상의 상위 뷰를 공유하는 두 뷰에 동일한 코드를 사용할 수 있습니다.

우선 자식보기 자동 크기 조정 비활성화

UIView *view1, *view2;
[childview setTranslatesAutoresizingMaskIntoConstraints:NO];
  1. UIView + Autolayout 또는 Purelayout 인 경우 :

    [view1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:view2];
    [view1 autoAlignAxis:ALAxisVertical toSameAxisOfView:view2];
    
  2. UIKit 레벨 자동 레이아웃 방법 만 사용하는 경우 :

    [view1 addConstraints:({
        @[ [NSLayoutConstraint
           constraintWithItem:view1
           attribute:NSLayoutAttributeCenterX
           relatedBy:NSLayoutRelationEqual
           toItem:view2
           attribute:NSLayoutAttributeCenterX
           multiplier:1.f constant:0.f],
    
           [NSLayoutConstraint
            constraintWithItem:view1
            attribute:NSLayoutAttributeCenterY
            relatedBy:NSLayoutRelationEqual
            toItem:view2
            attribute:NSLayoutAttributeCenterY
            multiplier:1.f constant:0.f] ];
    })];
    

2. 자동 레이아웃없이 :

나는 선호한다:

UIView *parentView, *childView;
[childView setFrame:({
    CGRect frame = childView.frame;

    frame.origin.x = (parentView.frame.size.width - frame.size.width) / 2.0;
    frame.origin.y = (parentView.frame.size.height - frame.size.height) / 2.0;

    CGRectIntegral(frame);
})];

The easiest way:

child.center = parent.center

여기에 이미지 설명을 입력하십시오

Set this autoresizing mask to your inner view.


With IOS9 you can use the layout anchor API.

The code would look like this:

childview.centerXAnchor.constraintEqualToAnchor(parentView.centerXAnchor).active = true
childview.centerYAnchor.constraintEqualToAnchor(parentView.centerYAnchor).active = true

The advantage of this over CGPointMake or CGRect is that with those methods you are setting the center of the view to a constant but with this technique you are setting a relationship between the two views that will hold forever, no matter how the parentview changes.

Just be sure before you do this to do:

        self.view.addSubview(parentView)
        self.view.addSubView(chidview)

and to set the translatesAutoresizingMaskIntoConstraints for each view to false.

This will prevent crashing and AutoLayout from interfering.


You can use

yourView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds))

And In Swift 3.0

yourView.center = CGPoint(x: superview.bounds.midX, y: superview.bounds.midY)

Using the same center in the view and subview is the simplest way of doing it. You can do something like this,

UIView *innerView = ....;
innerView.view.center = self.view.center;
[self.view addSubView:innerView];

Another solution with PureLayout using autoCenterInSuperview.

// ...
UIView *innerView = [UIView newAutoLayoutView];
innerView.backgroundColor = [UIColor greenColor];
[innerView autoSetDimensionsToSize:CGSizeMake(100, 30)];

[outerview addSubview:innerView];

[innerView autoCenterInSuperview];

This is it how it looks like:

PureLayout 센터


I would use:

child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)

이것은 간단하고 짧으며 달콤합니다. 위의 @Hejazi의 답변을 사용하고 하위보기 parent.center이외 (0,0)것으로 설정된 경우 중앙에 있지 않습니다!


c # 또는 Xamarin.ios에서는 다음과 같이 사용할 수 있습니다

imageView.Center = 새로운 CGPoint (tempView.Frame.Size.Width / 2, tempView.Frame.Size.Height / 2);


func callAlertView() {

    UIView.animate(withDuration: 0, animations: {
        let H = self.view.frame.height * 0.4
        let W = self.view.frame.width * 0.9
        let X = self.view.bounds.midX - (W/2)
        let Y = self.view.bounds.midY - (H/2)
        self.alertView.frame = CGRect(x:X, y: Y, width: W, height: H)
        self.alertView.layer.borderWidth = 1
        self.alertView.layer.borderColor = UIColor.red.cgColor
        self.alertView.layer.cornerRadius = 16
        self.alertView.layer.masksToBounds = true
        self.view.addSubview(self.alertView)

    })


}// calculation works adjust H and W according to your requirement

참고 URL : https://stackoverflow.com/questions/11251988/how-to-center-a-subview-of-uiview

반응형