programing

자동 레이아웃을 사용하여 전체 너비의 백분율을 만드는 방법은 무엇입니까?

minimums 2023. 5. 8. 22:00
반응형

자동 레이아웃을 사용하여 전체 너비의 백분율을 만드는 방법은 무엇입니까?

총 너비의 고정 비율을 가진 세 개의 동적 열을 만들어야 합니다.세 번째가 아니라 다른 가치관입니다.예를 들어, 다음 그림에서는 세 개의 열을 보여 줍니다. 첫 번째 열은 너비 42%, 두 번째 열은 너비 25%, 세 번째 열은 너비 33%입니다.

뷰 컨트롤러를 가로지르는 600픽셀의 경우, 이는 각각 252픽셀, 150픽셀 및 198픽셀입니다.

그러나 이후 디스플레이 크기(예: iPhone 4 가로(960 가로) 또는 iPad 2 세로(768 가로)의 경우 상대적 비율이 동일했으면 합니다(위에 인용된 픽셀 너비가 아님).

스토리보드(코드 없음)를 사용하여 이 작업을 수행할 수 있는 방법이 있습니까?코드로 쉽게 할 수 있지만, 제 목표는 가능한 한 많은 디스플레이 로직을 스토리보드에 넣는 것입니다.

여기에 이미지 설명 입력

만약 당신이 코드로 어떻게 하는지 안다면, 당신은 이미 스토리보드에서 어떻게 하는지 알고 있을 것입니다.이는 정확히 동일한 제약 조건이지만 코드가 아닌 시각적으로 제약 조건을 만듭니다.

  1. 보기와 해당 수퍼뷰를 모두 선택합니다.

  2. 너비가 수퍼뷰의 너비와 동일하도록 제한하려면 Editor -> Pin -> Width Equally(편집기 -> Width Equally)를 선택합니다(실제로 캔버스 하단의 "핀" 팝업 대화상자가 여기에서 가장 잘 작동합니다).

  3. 제약 조건을 편집하고 승수를 원하는 비율(예: 0.42)로 설정합니다.다른 관점들도 마찬가지입니다.

Apple이 UIStackView를 도입함에 따라 작업이 훨씬 쉬워졌습니다.

방법 1: 니브/스토리보드 사용:

인터페이스 빌더에서 3개의 뷰를 추가하고 스택 뷰에 포함하기만 하면 됩니다.

Xcode ► 편집기 ► StackView에 포함

여기에 이미지 설명 입력

stackView를 선택하고 선행, 후행, 상단 및 safeArea와 동일한 높이로 제약 조건을 지정합니다.

Attribute inspector 영역으로 클릭 & Set StackView 수평 분포를 비례적으로 채우도록 설정

[여기에 이미지 설명 입력3

세 개의 뷰에 대해 각 변의 선행, 후행, 상단, 하단의 제약 조건을 지정합니다.여기에 이미지 설명 입력

방법 2: 프로그래밍 방식:

import UIKit
class StackViewProgramatically: UIViewController {
    var propotionalStackView: UIStackView!
    ///Initially defining three views
    let redView: UIView = {
        let view = UIView()//taking 42 % initially
        view.frame = CGRect(x: 0, y: 0, width: 42 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
        view.backgroundColor = .red
        return view
    }()

    let greenView: UIView = {
        let view = UIView()//taking 42* initially
        view.frame = CGRect(x: 42 * UIScreen.main.bounds.width/100, y: 0, width: 25 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
        view.backgroundColor = .green
        return view
    }()
    let blueView: UIView = {
        let view = UIView()//taking 33*initially
        view.frame = CGRect(x: 67 * UIScreen.main.bounds.width/100, y: 0, width: 33 * UIScreen.main.bounds.width/100, height: UIScreen.main.bounds.height)
        view.backgroundColor = .blue
        return view
    }()

    ///Changing UIView frame to supports landscape mode.
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        DispatchQueue.main.async {
            self.redView.frame = CGRect(x: 0, y: 0, width: 42 * self.widthPercent, height: self.screenHeight)
            self.greenView.frame = CGRect(x: 42 * self.widthPercent, y: 0, width: 25 * self.widthPercent, height: self.screenHeight)
            self.blueView.frame = CGRect(x: 67 * self.widthPercent, y: 0, width: 33 * self.widthPercent, height: self.screenHeight)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //Adding subViews to the stackView
        propotionalStackView = UIStackView()
        propotionalStackView.addSubview(redView)
        propotionalStackView.addSubview(greenView)
        propotionalStackView.addSubview(blueView)
        propotionalStackView.spacing = 0
        ///setting up stackView
        propotionalStackView.axis = .horizontal
        propotionalStackView.distribution = .fillProportionally
        propotionalStackView.alignment = .fill
        view.addSubview(propotionalStackView)
    }
}
//MARK: UIscreen helper extension
extension NSObject {

    var widthPercent: CGFloat {
        return UIScreen.main.bounds.width/100
    }

    var screenHeight: CGFloat {
        return UIScreen.main.bounds.height
    }
}

출력:

풍경화 및 초상화 작업

여기에 이미지 설명 입력 여기에 이미지 설명 입력

데모 프로젝트 - https://github.com/janeshsutharios/UIStackView-with-constraints

https://developer.apple.com/videos/play/wwdc2015/218/

슈퍼뷰 내에서 고정 비율 레이아웃이 필요한 임의의 뷰에 보다 쉽게 적용할 수 있도록 보다 자세히 설명할 수 있다고 생각합니다.

맨 왼쪽 보기

  • SuperView.Leading
  • 고정 백분율을 에서 곱셈기로 정의합니다.SuperView.Height

중간 보기

  • 고정 백분율을 에서 곱셈기로 정의합니다.SuperView.Height
  • 을 핀으로 합니다.left그 이웃의 오른쪽에.

오른쪽 끝 보기

  • 고정 백분율을 정의하지 않습니다(사용 가능한 보기의 나머지).
  • 을 핀으로 합니다.left그 이웃의 오른쪽에.
  • 을 핀으로 합니다.rightSuperView.Trailing

모든 뷰

  • 되지 않은 는 고되지않높다고음정정다의니합여하에이를은정에 고정하여 정의합니다.Top Layout Guide.Top그리고.Top Layout Guide.bottom위의 답변에서는 인접 보기와 동일한 높이를 설정하여 이 작업을 수행할 수도 있습니다.

언급URL : https://stackoverflow.com/questions/26373598/how-to-create-percentage-of-total-width-using-autolayout

반응형