가변 크기 이미지에 AutoLayout의 최적 텍스트 배치

10316 단어 AutoLayoutSwift

제목.


이런 명품.png에 사용자가 입력한 텍스트를 설정하는 방법
  • 이미지 크기 변경 가능
  • 실장 의 비결


    AutoLayout의 Multiplier를 사용하여 이미지 크기에서 백분율 위치를 지정할 수 있습니다.

    지정 방법


    먼저 UIlabel 구성 준비

  • 너비에 따라 font 사이즈를 조정하여 명품adjustsFontSizeToFitWidthtrue
  • 초과를 방지한다.
  • minimumScaleFactor에서 최소 글꼴 크기 지정
  • var nameLabel: UILabel = {
        let lb = UILabel()
        lb.text = "きんにくひろし"
        lb.numberOfLines = 1
        lb.font = UIFont.boldSystemFont(ofSize: 48)
        lb.adjustsFontSizeToFitWidth = true
        lb.minimumScaleFactor = 8 / lb.font.pointSize
        return lb
    }()
    

    AutoLayout 지정

    translatesAutoresizingMaskIntoConstraints: falseNSLayoutConstraint로 Layout 진행multiplier 모원소의 백분율 상대 위치를 지정하는 데 사용됩니다.
    ※ 이때left margin는 부요소right margin를 대상으로 지정할 수 있습니다.left margin를 대상으로 지정하면 시작점 0이기 때문에 레이아웃이 작동하지 않습니다.
    ※ 위아래 좌우 여백을 지정하지 않으면 텍스트는adjust가 되지 않습니다
    nameLabel.translatesAutoresizingMaskIntoConstraints = false
    
    // 名前LabelのAutoLayout
    
    imageView.addConstraints([
        // top
        NSLayoutConstraint(
            item: nameLabel,
            attribute: .top,
            relatedBy: .equal,
            toItem: imageView,
            attribute: .bottom,
            multiplier: 0.65,
            constant: 0
        ),
        // bottom
        NSLayoutConstraint(
            item: nameLabel,
            attribute: .bottom,
            relatedBy: .equal,
            toItem: imageView,
            attribute: .bottom,
            multiplier: 0.85,
            constant: 0
        ),
        // left
        NSLayoutConstraint(
            item: nameLabel,
            attribute: .left,
            relatedBy: .equal,
            toItem: imageView,
            attribute: .right,
            multiplier: 0.23,
            constant: 0
        ),
        // right
        NSLayoutConstraint(
            item: nameLabel,
            attribute: .right,
            relatedBy: .equal,
            toItem: imageView,
            attribute: .right,
            multiplier: 0.7,
            constant: 0
        )
    ])
    

    완성


    기초적인 이미지 크기가 변해도 텍스트는 예쁘게 수납되어 있다
    Custom View를 사용하면 여러 화면에서 사용하기 편리합니다.
    Landscape
    Portrait


    Multiplier의 값은 어떻게 결정합니까?


    Zeplin으로 쉽게 떼어낼 수 있어요.Alt를 누르면 확인하고 싶은margin 근처로 커서를 옮길 때 부모 요소에서
    margin을% 표시할 수 있기 때문에 그것을 사용하십시오.

    (스케치도 가능. 살짝 건드리면% 표시 불가)

    사은품: SnapKit를 사용한 실크


    41줄->6줄만 적으면 편해요.
    // 名前LabelのAutoLayout
    nameLabel.snp.makeConstraints { (make) in
        make.top.equalTo(imageView.snp.bottom).multipliedBy(0.65)
        make.bottom.equalTo(imageView.snp.bottom).multipliedBy(0.85)
        make.left.equalTo(imageView.snp.right).multipliedBy(0.23)
        make.right.equalTo(imageView.snp.right).multipliedBy(0.7)
    }
    

    좋은 웹페이지 즐겨찾기