Objective-C中如何为UITableViewCell内菜单按钮的下拉UITableView设置Frame
嘿,这个需求我刚好做过类似的,给你梳理几个关键步骤,帮你搞定这个下拉菜单的Frame设置:
核心思路:锚定Cell位置 + 匹配内容尺寸
下拉菜单的位置完全依赖于点击的那个Cell在屏幕上的实际坐标,再结合它自身的内容高度(3行)来确定Frame,具体操作如下:
1. 先拿到点击Cell的全局屏幕坐标
当用户点击Cell里的菜单按钮时,先定位到当前按钮所属的Cell,再把Cell的本地坐标转换成全局坐标系下的位置:
// 假设按钮点击事件的sender是UIButton guard let cell = sender.findSuperview(ofType: YourTableViewCell.self) else { return } // 将Cell的frame转换为window坐标系下的位置 let cellGlobalFrame = yourMainTableView.convert(cell.frame, to: nil) // 这里给你补个递归找父视图的工具方法,比硬写superview靠谱 extension UIView { func findSuperview<T: UIView>(ofType type: T.Type) -> T? { guard let superview = superview else { return nil } return superview as? T ?? superview.findSuperview(ofType: type) } }
2. 计算下拉TableView的固定尺寸
因为下拉菜单是固定3行,直接用行高乘以3就能得到高度,宽度一般和主TableView或Cell对齐:
// 宽度和主TableView保持一致,也可以根据需求调整左右边距 let dropDownWidth = yourMainTableView.bounds.width // 自定义行高或者用系统默认的44 let rowHeight: CGFloat = 44 let dropDownHeight = rowHeight * 3
3. 精准设置下拉菜单的Frame
把Cell的底部作为下拉菜单的顶部起点,结合计算好的尺寸设置Frame:
let dropDownFrame = CGRect( x: cellGlobalFrame.origin.x, y: cellGlobalFrame.origin.y + cellGlobalFrame.size.height, width: dropDownWidth, height: dropDownHeight ) yourDropDownTableView.frame = dropDownFrame
如果想要下拉菜单和Cell有左右边距,比如缩进8pt,只需要修改x和width:x: cellGlobalFrame.origin.x + 8、width: dropDownWidth - 16
4. 滚动时同步更新位置(必加优化)
当主TableView滚动时,下拉菜单的位置会跑偏,所以要监听滚动事件实时更新:
// 先在点击按钮时保存选中的Cell private var selectedCell: YourTableViewCell? // 然后在scrollViewDidScroll里更新Frame func scrollViewDidScroll(_ scrollView: UIScrollView) { guard let cell = selectedCell else { return } let cellGlobalFrame = yourMainTableView.convert(cell.frame, to: nil) var updatedFrame = yourDropDownTableView.frame updatedFrame.origin.y = cellGlobalFrame.origin.y + cellGlobalFrame.size.height yourDropDownTableView.frame = updatedFrame }
额外提醒
- 下拉TableView的父视图建议设为
UIWindow或者主TableView的父视图,避免被Cell或主TableView的滚动遮挡; - 如果Cell是动态高度,记得在获取
cellGlobalFrame前调用cell.layoutIfNeeded(),确保拿到的是布局完成后的真实Frame。
内容的提问来源于stack exchange,提问作者9121989
相关产品推荐
相关产品推荐

