문자열의 길이와 크기에 따라 UIlabel의 디스플레이 영역을 자동으로 조정하고 TableViewCell의 Height도 이에 따라 자동으로 조정(iOS 8 이상)

3119 단어 SwiftiOS

AutoLayout Settings



UITableViewCell

class DynamicHeightCell: UITableViewCell {
    @IBOutlet var label1: UILabel!
    @IBOutlet var label2: UILabel!

    override func layoutSubviews() {
        super.layoutSubviews()

        // NOTE: If an app runs on iOS9 or more, these codes are unnecessary.
        self.label1.preferredMaxLayoutWidth = CGRectGetWidth(self.label1.bounds)
        self.label2.preferredMaxLayoutWidth = CGRectGetWidth(self.label2.bounds)
    }

    func setup(val1: String) {
        self.setup(val1: val1, val2: val1)
    }
    func setup(val1 val1: String, val2: String) {
        self.label1.text = val1
        self.label1.numberOfLines = 0 // Or, you can set it on a storyboard.
        self.label2.text = val2
        self.label2.numberOfLines = 0 // Or, you can set it on a storyboard.

        self.label1.hidden = "" == self.label1.text
        self.label2.hidden = "" == self.label2.text
    }
}

UITableView (or UITableViewController)

class TableViewHasDynamicHeightCellViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 160.0
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TestCell") as! DynamicHeightCell

        let type = indexPath.row % 5

        switch type {
        case 0:
            cell.setup("TEST0")
            break
        case 1:
            cell.setup(val1: "TEST1", val2: "あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも わをん")
            break
        case 2:
            cell.setup(val1: "", val2: "TEST2")
            break
        case 3:
            cell.setup("あいうえお\nかきくけこ\nさしすせそ")
            break
        case 4:
            cell.setup(val1: "TEST4", val2: "")
            break
        default:
            cell.setup("TEST CELL is default.")
            break
        }

        return cell
    }
}

NOTE

  • If an app runs on iOS7 or more, see http://qiita.com/nari6a/items/e9b83aa4488e43b79da8
  • 좋은 웹페이지 즐겨찾기