UFO ET IT

iOS AutoLayout-프레임 크기 너비 가져 오기

ufoet 2020. 12. 13. 10:01
반응형

iOS AutoLayout-프레임 크기 너비 가져 오기


iOS 6 자동 레이아웃을 사용하여 개발 중입니다.

보기의 프레임 너비를 표시하는 메시지를 기록하고 싶습니다.

화면에서 textView를 볼 수 있습니다.

하지만 너비와 높이가 0으로 표시됩니다.

NSLog(@"textView    = %p", self.textView);
NSLog(@"height      = %f", self.textView.frame.size.height);
NSLog(@"width       = %f", self.textView.frame.size.width);

textView    = 0x882de00
height      = 0.000000
width       = 0.000000

나는 당신이 이것을 호출 할 때까지 자동 레이아웃이 뷰를 레이아웃 할 시간이 없다고 생각합니다. viewDidLoad뷰가로드 된 직후 호출되고 뷰가 뷰 컨트롤러의 뷰 계층 구조에 배치되고 결국 레이아웃 (뷰의 layoutSubviews메서드에서) 되기 때문에 자동 레이아웃 이 호출 될 때까지 발생하지 않았습니다 .

편집 :이 답변은 질문의 시나리오가 작동하지 않는 이유를 지적합니다. @dreamzor의 답변 은 문제를 해결하기 위해 코드를 어디에 배치 해야하는지 알려 줍니다.


실제로 위의 답변은 옳지 않습니다. 나는 그들을 따라 갔고 몇 번이고 0을 얻었습니다.

트릭은 프레임 종속 코드를 viewDidLayoutSubviews메서드에 배치하는 것입니다.

뷰 컨트롤러에 뷰가 하위 뷰를 배치했음을 알립니다.

이 메서드는 여러 번 호출되고 ViewController의 수명주기의 일부가 아니라는 점을 잊지 마십시오. 사용시주의하십시오.

누군가에게 도움이되기를 바랍니다.

그냥 추가하고 싶었습니다. 가로 모드가없는 내 프로그램의 경우 자동 레이아웃을 사용하지 않는 것이 훨씬 간단합니다 ... 나는 시도했지만 = D


viewDidLoad ()에 포함

self.view.setNeedsLayout()
self.view.layoutIfNeeded()

yourview.frame.size.width에 액세스하기 전에


해결책

  • 해당 코드를 viewDidAppear

이유

  • viewDidLoad자동 레이아웃이 완료되기 전에 발생합니다. 따라서 위치는 아직 xib에 지정된 자동 레이아웃으로 설정되지 않았습니다.
  • viewDidAppear 자동 레이아웃이 완료된 후 발생합니다.

실제로 나는 내 코드 전에 레이아웃 업데이트 강제로 관리 했습니다 viewDidLoad.

override func viewDidLoad() {
        super.viewDidLoad()

        println("bounds before \(self.previewContainer.bounds)");
        //on iPhone 6 plus -> prints bounds before (0.0,0.0,320.0,320.0)

        self.view.setNeedsLayout()
        self.view.layoutIfNeeded()

        println("bounds after \(self.previewContainer.bounds)");
        //on iPhone 6 plus -> prints bounds after (0.0,0.0,414.0,414.0)

        //Size dependent code works here
        self.create()
    }

업데이트 : 이것은 더 이상 작동하지 않는 것 같습니다.


이것은 정말 이상한 기능입니다. 그러나 나는 발견했다 :

layoutsubviews 메소드를 사용하지 않고 프레임을 얻으려면 다음을 사용하십시오.

dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"View frame: %@", NSStringFromCGRect(view.frame));
    });

정말 이상 해요 !!!


위의 답변 중 어느 것도 나를 위해 완전히 작동 viewDidLoad하지 않았지만 뷰가 애니메이션으로 표시 될 때까지 내가 원하는 것을 표시하지 않는 부작용이 있습니다.

viewDidLayoutSubviews 완료되는 자동 레이아웃에 의존하는 코드를 실행하는 올바른 위치 여야 하지만 다른 사람들이 지적했듯이 최근 iOS 버전에서는 여러 번 호출되고 어떤 것이 최종 호출인지 알 수 없습니다.

So I resolved this with a small hack. In my storyboard, mySubview should be smaller than its containing self.view. But when viewDidLayoutSubviews is first called, mySubview still has a width of 600, whereas self.view seems to be set correctly (this is an iPhone project). So all I have to do is monitor subsequent calls and check the relative widths. Once mySubview is smaller than self.view I can be sure it has been laid out correctly.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if self.mySubview.bounds.size.width < self.view.bounds.size.width {

        // mySubview's width became less than the view's width, so it is
        // safe to assume it is now laid out correctly...

    }
}

This has the advantage of not relying on hard-coded numbers, so it can work on all iPhone form factors, for example. Of course it may not be a panacea in all cases or on all devices, but there are probably many ingenious ways to do similar checks of relative sizes.

And no, we shouldn't have to do this, but until Apple gives us some more reliable callbacks, we're all stuck with it.


iOS AutoLayout - get frame size width

 -(void) layoutSubviews{
        [self layoutIfNeeded];
        //right you code to set frame its will work to get frame and set frame.
        CALayer *bottomBorder = [CALayer layer];
        bottomBorder.frame = CGRectMake(0.0f, bkView.frame.size.height - 1, bkView.frame.size.width, 1.0f);
        bottomBorder.backgroundColor = [UIColor blackColor].CGColor;
        [bkView.layer addSublayer:bottomBorder];
    }

You can only find out the size after the first layout pass. Or Just call below method then after you got actual width of you view.

[yourView layoutIfNeeded];

참고URL : https://stackoverflow.com/questions/12527191/ios-autolayout-get-frame-size-width

반응형