3
2

More than 3 years have passed since last update.

Swiftで可変のラベルが入ったスクロールビューの高さをAutoLayoutで調整する

Posted at

やりたいことの概要

1画面では収まり切らないとても長い文章を表示するときに、UIScrollViewは便利です。しかしその文章の長さを後で変えたり、異なるデバイスで見る際は、UILabelの高さを明確に決められません。

自分が作成したマッチングアプリの利用規約を載せるときに、この問題にあたりました。最初は大きめに高さを確保する方法を採用しましたが、最後までスクロールしたときに謎な空白ができてしまいます。

今回はコードによるオートレイアウトのみで、scrollViewのcontentSizeを最適化する方法をまとめます。

コード

Rule.swift
import Foundation
import UIKit

class RuleView: UIView {

    let scrollView = UIScrollView()
    let label = UILabel()

    required override init(frame:CGRect){
        super.init(frame:frame)
        backgroundColor = .white
        addSubview(scrollView)
        scrollView.addSubview(label)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        scrollView.frame = frame
        scrollView.contentSize.width = frame.width
        scrollView.bounces = false
        scrollView.indicatorStyle = .default
        scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        scrollView.backgroundColor = UIColor.white

        label.font = UIFont.systemFont(ofSize: 15.0)
        label.backgroundColor = .white
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        label.firstBaselineAnchor.constraint(equalTo: self.topAnchor, constant: 30.0).isActive = true
        label.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10.0).isActive = true
        label.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10.0).isActive = true
    }

    //ViewControllerから呼び出される
    func setText(text: String) {
        label.text = text
        label.sizeToFit()
     //下に空けたい隙間によって値を調節する
        label.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -100.0).isActive = true
    }


}

labelとscrollViewの高さは最初は指定せず、textが渡された時点でlabelの高さを決めて、最後にscrollViewの下端とlabelの下端の距離を調節します。

この順番を変えるとエラーがおきました。setTextは何回呼び出してもいいので、途中でテキストが変わる場合も安心です。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2