IOS Swift3.0 TableViewCell自定义高度

本文主要介绍了如何在Swift 3.0和Xcode 8.2.1环境下,为UITableViewCell设置自定义高度。关键步骤包括设置tableView的estimatedRowHeight和rowHeight属性,避免重写heightForRowAt方法,以及确保正确的布局约束以实现'首尾相连'。特别强调了布局顺序的重要性,以及如何处理UILabel和UIImageView以适应不同内容和图片大小。
摘要由CSDN通过智能技术生成

其实,写这篇博客目的呢,就是给ios新手们提供一些帮助吧,少走些弯路。当然这都是小技巧了,大家仔细琢磨一下就会懂的。那言归正传,接下来,我就说下我学到的东西。

工具:Xcode 8.2.1版本

语言:Swift 3.0版本

目标:实现TableViewCell自定义高度


一个ViewController视图控制器文件,如下:

//
//  ViewController.swift
//  TableCustom
//
//  Created by WangShuai on 17/3/21.
//  Copyright © 2017年 cn.com.yisquare. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    let tableView = UITableView()
    let heightList = [50, 100, 150, 200, 250]
    let list = ["打喷嚏是一想二骂三感冒", "打喷嚏是一想二骂三感冒,打喷嚏是一想二骂三感冒", "打喷嚏是一想二骂三感冒,打喷嚏是一想二骂三感冒,打喷嚏是一想二骂三感冒", "2015年7月26日 - swift UITableView cell自适应高度 2015-07-26 22:50 4050人阅读 评论(0) 收藏 举报 分类: ios(21) 作者同类文章X 版权声明:本文为博主原创文章,转载", "2016年9月6日 - 自定义了一个UITableViewCell用于展示一些新闻信息,类似于图里的样子,Cell里的内容不是固定的,有时候有图片有时候没有图片,标题和说明文字的长度也不确定。"]
    let cellIdentifier: String = "cellIdentifier"

    override func viewDidLoad() {
        super.viewDidLoad()
        print("测试TableView自定义高度")
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.dataSource = self
        tableView.delegate = self
        self.automaticallyAdjustsScrollViewInsets = false
        tableView.separatorStyle = .none
        tableView.register(Cell.self, forCellReuseIdentifier: "cellIdentifier")
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        self.view.addSubview(tableView)
        self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0.0))
        self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1.0, constant: 20.0))
        self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1.0, constant: 0.0))
        self.view.addConstraint(NSLayoutConstraint(item: tableView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 1.0, constant: 0.0))
        
        
    }

    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值