【swift】tableview

本文介绍了在Swift中使用UITableView时如何实现UITableViewCell的自适应高度,包括设置estimatedRowHeight和rowHeight属性的方法,以及通过tableView(_:heightForRowAt:)函数动态调整行高。同时,文章还提到了关闭键盘的手势和滑动页面关闭键盘的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cell自适应高度

方案1:

lazy var tableView : UITableView = {
     let tableView = UITableView.init(frame: CGRect(x:0, y:SCREEN_NAVIGATION_HEIGHT + 97, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-SCREEN_NAVIGATION_HEIGHT-SCREEN_TABBAR_HEIGHT - 97), style: UITableView.Style.plain)
     tableView.delegate = self
     tableView.dataSource = self
     tableView.backgroundColor = UIColor.white
     tableView.separatorStyle = .none
     tableView.isHidden = true
     tableView.register(PeopleListCell.self, forCellReuseIdentifier: "PeopleListCellIdentifier")
     tableView.keyboardDismissMode = UIScrollView.KeyboardDismissMode.onDrag
     //这里开始设置cell自适应高度
     tableView.estimatedRowHeight = 44.0;	         				
     tableView.rowHeight = UITableView.automaticDimension;
     //这里结束设置cell自适应高度
     return tableView
}()

方案2:

//estimate height
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
   return 120
}
    
//table高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

滑动页面关闭键盘

//tableview滚动关闭键盘
tableView.keyboardDismissMode = UIScrollView.KeyboardDismissMode.onDrag
//scrollView滚动关闭键盘
scrollView.keyboardDismissMode = UIScrollView.KeyboardDismissMode.onDrag

手势

//UIGestureRecognizer类用于手势识别,它的子类有主要有六个分别是:
//UITapGestureRecognizer(轻击一下)
//UIPinchGestureRecognizer(两指控制的缩放)
//UIRotationGestureRecognizer(旋转)
//UISwipeGestureRecognizer(滑动,快速移动)
//UIPanGestureRecognizer(拖移,慢慢移动)
//UILongPressGestureRecognizer(长按)

view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap:"))  
func handleTap(sender: UITapGestureRecognizer) {  
     if sender.state == .Ended {  
        print("收回键盘")  
       workcontent.resignFirstResponder()  
     }  
     sender.cancelsTouchesInView = false  
 }  

cell 编辑

//开启编辑功能
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}
//设置删除按钮的title,此处为"Delete"
func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
    return "Delete"
}
//点击方法
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCell.EditingStyle.delete {
        /// here is your code
		//删除当前cell
        tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值