티스토리 뷰

iOS

오토레이아웃 정복하기#1

learner._.Kio 2021. 4. 1. 02:19
 

오토레이아웃 정복하기 - 야곰닷넷

오토레이아웃 정복하기 온라인 코스입니다.

yagom.net

 

Understanding Auto Layout

[공식에서 보는 Auto Layout이란?]

 

Understanding Auto Layout

Auto Layout dynamically calculates the size and position of all the views in your view hierarchy, based on ★constraints placed on those views. For example, you can constrain a button so that it is horizontally centered with an Image view and so that the button’s top edge always remains 8 points below the image’s bottom. If the image view’s size or position changes, the button’s position automatically adjusts to match.

 

This constraint-based approach to design allows you to build user interfaces that dynamically respond to both internal and external changes.

External Changes

External changes occur when the size or shape of your superview changes. With each change, you must update the layout of your view hierarchy to best use the available space. Here are some common sources of external change:

  • The user resizes the window (OS X).
  • The user enters or leaves Split View on an iPad (iOS).
  • The device rotates (iOS).
  • The active call and audio recording bars appear or disappear (iOS).
  • You want to support different size classes.
  • You want to support different screen sizes.

Most of these changes can occur at runtime, and they require a dynamic response from your app. Others, like support for different screen sizes, represent the app adapting to different environments. Even through the screen size won’t typically change at runtime, creating an adaptive interface lets your app run equally well on an iPhone 4S, an iPhone 6 Plus, or even an iPad. Auto Layout is also a key component for supporting Slide Over and Split Views on the iPad. 

Internal Changes

Internal changes occur when the size of the views or controls in your user interface change.

Here are some common sources of internal change:

  • The content displayed by the app changes.
  • The app supports internationalization.
  • The app supports Dynamic Type (iOS)

Auto Layout Versus Frame-Based Layout

오토레이아웃의 출발점!


Anatomy of a Constraint

1. Attributes (제약 조건의 속성)

Blue와 Red

  • 8 = 8 point
  • 위 식을 이처럼 나타낼수 있다. y = mx + c

  • 미국 기준이어서 왼쪽이 Leading, 오른쪽이 Trailing이다. (아랍이었다면 반대였을 것)
  • Left or Leading: 글이 시작하는 방향을 뜻한다.
  • Right or Trailing: 글을 읽는 방향을 뜻한다.

 

  •  

2. Sample Equations (간단한 방정식)

  • Size Attribute
    • Width
    • Height
  • Location Attribute
    • Top, Bottom
    • Center X, Y
    • Left or Leading / Right or Trailing
    • Baseline

Size Attribute와 Location Attribue의 차이점

(With these differences in mind, the following rules apply:)

  • You cannot constrain a size attribute to a location attribute.
  • You cannot assign constant values to location attributes.
  • You cannot use a nonidentity multiplier (a value other than 1.0) with location attributes.
  • For location attributes, you cannot constrain vertical attributes to horizontal attributes.
  • For location attributes, you cannot constrain Leading or Trailing attributes to Left or Right attributes.

제한 예시 (Sample equations for common constraints)

// y = mx + c
// '=' 의 뜻은 할당이 아닌 같다는 표현이다.

// Setting a constant height
View.height = 0.0 * NotAnAttribute + 40.0
// view의 높이는 40이다.
 
// Setting a fixed distance between two buttons
Button_2.leading = 1.0 * Button_1.trailing + 8.0
// Button_2의 leading 위치는 Button_1의 trailing에서 8만큼 떨어져있다.
 
// Aligning the leading edge of two buttons
Button_1.leading = 1.0 * Button_2.leading + 0.0
// unline, 정렬
 
// Give two buttons the same width
Button_1.width = 1.0 * Button_2.width + 0.0
// Button_1과 Button_2의 너비는 같다.
 
// Center a view in its superview
View.centerX = 1.0 * Superview.centerX + 0.0
View.centerY = 1.0 * Superview.centerY + 0.0
// superview와 view
 
// Give a view a constant aspect ratio
View.height = 2.0 * View.width + 0.0
// View의 높이는 가로보다 2배 크다.

Inverted equations

// '=' 의 뜻은 할당이 아닌 같다는 표현이다.

// Setting a fixed distance between two buttons
Button_1.trailing = 1.0 * Button_2.leading - 8.0
 
// Aligning the leading edge of two buttons
Button_2.leading = 1.0 * Button_1.leading + 0.0
 
// Give two buttons the same width
Button_2.width = 1.0 * Button.width + 0.0
 
// Center a view in its superview
Superview.centerX = 1.0 * View.centerX + 0.0
Superview.centerY = 1.0 * View.centerY + 0.0
 
// Give a view a constant aspect ratio
View.width = 0.5 * View.height + 0.0

 

3. Creating Nonambiguous Layouts (명확한 레이아웃 만들기)

x축에 한해서

  • The first layout constrains the view’s leading edge relative to its superview’s leading edge. It also gives the view a fixed width. The position of the trailing edge can then be calculated based on the superview’s size and the other constraints.
  • The second layout constrains the view’s leading edge relative to its superview’s leading edge. It also constrains the view’s trailing edge relative to the superview’s trailing edge. The view’s width can then be calculated based on the superview’s size and the other constraints.
  • The third layout constrains the view’s leading edge relative to its superview’s leading edge. It also center aligns the view and superview. Both the width and trailing edge’s position can then be calculated based on the superview’s size and the other constraints. 
    • → 제약을 줄 때는 X, Y축에 둘 다 주고, 위치와 크기를 알아야한다.

 

4. Variety Solutions

제약

  • 제약을 아래의 그림(제약A)처럼 줄 수 있다.
  • 제약을 수정할 때는 그림(제약B)처럼 해줘야 한다. 

제약A
제약B

 

5. Constraints on Storyboard

The above solution uses the following constraints:

// Vertical Constraints
Red.top = 1.0 * Superview.top + 20.0
Superview.bottom = 1.0 * Red.bottom + 20.0
Blue.top = 1.0 * Superview.top + 20.0
Superview.bottom = 1.0 * Blue.bottom + 20.0
 
// Horizontal Constraints
Red.leading = 1.0 * Superview.leading + 20.0
Blue.leading = 1.0 * Red.trailing + 8.0
Superview.trailing = 1.0 * Blue.trailing + 20.0
Red.width = 1.0 * Blue.width + 0.0

 

BUT WHICH IS BETTER?

These solutions both produce valid layouts. So which is better?

 

Unfortunately, it is virtually impossible to objectively prove that one approach is strictly superior to the other. Each has its own strengths and weaknesses.

 

The first solution is more robust when a view is removed. Removing a view from the view hierarchy also removes all the constraints that reference that view. So, if you remove the red view, the blue view is left with three constraints holding it in place. You need to add only a single constraint and you have a valid layout again. In the second solution, removing the red view would leave the blue view with only a single constraint.

 

On the other hand, in the first solution, If you want the top and bottom of the views to align, you must make sure their top and bottom constraints use the same constant value. If you change one constant, you must remember to change the other as well.

→ 정답은 없다.

6. Constraint Priorities (제약 우선도)

Constraint Inequalities

So far, all of the samples have shown constraints as equalities, but this is only part of the story. Constraints can represent inequalities as well. Specifically, the constraint’s relationship can be equal to, greater than or equal to, or less than or equal to.

For example, you can use constraints to define the minimum or maximum size for a view (Listing 3-3).

 

Listing 3-3 Assigning a minimum and maximum size

// Setting the minimum width
View.width >= 0.0 * NotAnAttribute + 40.0
 
// Setting the maximum width
View.width <= 0.0 * NotAnAttribute + 280.0

 

Constraint Priorities

By default, all constraints are required. Auto Layout must calculate a solution that satisfies all the constraints. If it cannot, there is an error. Auto Layout prints information about the unsatisfiable constraints to the console, and chooses one of the constraints to break. It then recalculates the solution without the broken constraint. For more information, see Unsatisfiable Layouts.

You can also create optional constraints. All constraints have a priority between 1 and 1000. Constraints with a priority of 1000 are required. All other constraints are optional.

 

NOTE.

Don’t feel obligated to use all 1000 priority values. In fact, priorities should general cluster around the system-defined low (250), medium (500), high (750), and required (1000) priorities. You may need to make constraints that are one or two points higher or lower than these values, to help prevent ties. If you’re going much beyond that, you probably want to reexamine your layout’s logic.

 

For a list of the predefined constraint constants on iOS, see the UILayoutPriority enum. For OS X, see the Layout Priorities constants.

  • 동일한 우선도라면 충돌이 일어난다.
  • 싸울일이 없다면 둘 다 충족하는 결과가 일어난다.
    • Relation, Priority

 

7. Intrinsic Content Size (고유 컨텐츠 크기)

Intrinsic Content Size

So far, all of the examples have used constraints to define both the view’s position and its size. However, some views have a natural size given their current content. This is referred to as their intrinsic content size. For example, a button’s intrinsic content size is the size of its title plus a small margin.

 

Not all views have an intrinsic content size. For views that do, the intrinsic content size can define the view’s height, its width, or both. Some examples are listed in Table 3-1.

 

Table 3-1Intrinsic content size for common controlsViewIntrinsic content size

The intrinsic content size is based on the view’s current content. A label or button’s intrinsic content size is based on the amount of text shown and the font used. For other views, the intrinsic content size is even more complex. For example, an empty image view does not have an intrinsic content size. As soon as you add an image, though, its intrinsic content size is set to the image’s size.

  • Label, Button은 제약을 주면 바로 이동한다.
  • View, Slider는 자신의 사이즈를 몰라서 오류가 난다.
    • place holder로 임시적으로 조정할 수 있지만, 이것은 실제 앱을 실행할 때는 적용되지 않는다.
    • cocoa file로 아래처럼 하고 클래스를 지정하면 조정할 수 있다.
import UIKit

@IBDesignable
class MyView: UIView {

    override var intrinsicContentSize: CGSize {
        return CGSize(width: 50, height: 50)
    }
}

 

 

8. CHCR 

Compression-Resistance and Content-Hugging equations: 줄어들지 않으려고 버티는 힘

Content hugging 늘어나는 것을 방지하는 힘

Compression-Resistance

 


Working in Interface Builder

Add New Alignment Constraints

Add New Constraints

비추! 컴퓨터를 믿으면 안된다.

  • Add Missing Constraints
  • Reset to Suggested Constraints

ctrl + 마우스 클릭으로도 제약을 줄 수 있다.

  • opt 키를 누르면 추가적인 옵션이 있다!


Simple Constraints

1:2 크기로 맞춰보기

Purple View.Leading = Superview.LeadingMargin

Orange View.Leading = Purple View.Trailing + Standard

Orange View.Trailing = Superview.TrailingMargin

Purple View.Top = Top Layout Guide.Bottom + 20.0

Orange View.Top = Top Layout Guide.Bottom + 20.0

Bottom Layout Guide.Top = Purple View.Bottom + 20.0

Bottom Layout Guide.Top = Orange View.Bottom + 20.0

Orange View.Width = 2.0 x Purple View.Width

 

 multiplier를 조절하는 다양한 방법

Discussion

This recipe uses a multiplier on the width constraint. Multipliers can only be used on constraints to a view’s height or width. It lets you set the relative size of two different views. Alternatively, you can set a constraint between the view’s own height and width, specifying the view’s aspect ratio.

 

Interface Builder lets you specify the multiplier using a number of different formats. You can write the multiplier as a decimal number (2.0), a percentage (200%), a fraction (2/1), or a ratio (2:1).

 

 

Left view 최소 가로 길이 150 맞춰보기

가로모드 / 세로모드 적용!


[Challenge] Profile View


Stack View

 

1. Understanding Stack View 

stack view에 대해 더 들어보고 싶다면 WWDC15 218 session 들어보기

  • axis: (UIStackView only) defines the stack view’s orientation, either vertical or horizontal.
    • Horizontal, Vertical
  • orientation: (NSStackView only) defines the stack view’s orientation, either vertical or horizontal.
  • distribution: defines the layout of the views along the axis.
  • alignment: defines the layout of the views perpendicular to the stack view’s axis.
  • spacing: defines the space between adjacent views.

Stack View Properties

  • distribution: UIStackeView.Distribution
    • fill
    • fillEqually
    • fillProportionally: 비율대로
    • equalSpacing
    • equalCentering

fill
fillEqually
fillProportionally
equalSpacing
equalCentering

  • alignment: UIStackView.Alignment
    • fill
    • leading
    • top
    • firstBaseline
    • center
    • trailing
    • bottom
    • lastBaseline

fill
leading
top
firstBaseline
center
trailing
bottom
lastBaseline

  • spacing: CGFloat

 

2. Simple Stack View

 

댓글