简介
UIScrollView、UICollectionView、UITableView这些视图,是最常用的视图类;但是我对它们是又爱又恨,在应用的过程中,会出现各种意想不到的惊喜。这篇文章用于记录,上述三个类的顶部空白的解决方法。
1.UIScrollView顶部空白的相关属性
1.1 automaticallyAdjustsScrollViewInsets属性:
是iOS7以后UIViewController的新增属性;
在iOS11以后废除;
当设置为YES时(默认YES),如果视图里面存在唯一一个UIScrollView或其子类View,那么它会自动设置相应的内边距,这样可以让scroll占据整个视图,又不会让导航栏遮盖。
1.2 contentInsetAdjustmentBehavior属性:
是iOS11新增的UIScrollView的属性;
是对废除automaticallyAdjustsScrollViewInsets的增进补充;
当该属性的制为.never时,与automaticallyAdjustsScrollViewInsets为NO时,效果相同,即不考虑顶部导航栏和安全区域等因素,填充满整个视图
UICollectionView、UITableView是UIScrollView的子视图,设置该属性与UIScrollView效果等同。
1.3 代码设置上述属性
if #available(iOS 11, *) {
//系统版本高于11
tableView.contentInsetAdjustmentBehavior = .never
}
else {
self.automaticallyAdjustsScrollViewInsets = false
}
2.UITableView顶部空白的相关设置和方法
2.1影响UITableView顶部空白的因素
1.contentInsetAdjustmentBehavior或者automaticallyAdjustsScrollViewInsets属性的设置,同UIScrollView;
2.tableHeaderView属性的设置;
3.UITableView分区头部视图sectionHeader的设置;
2.2代码设置上述属性和方法
tableView.tableHeaderView = nil // 在iOS12以前,该操作会导致tableView顶部空白
tableView.tableHeaderView = UIView.init() // 在iOS12以前,该操作会导致tableView顶部空白
tableView.tableHeaderView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: CGFloat.leastNonzeroMagnitude)) // 该操不会导致tableView顶部空白
同理,tableFooterView也是如此。footer和header只要设置了任意一个都会使两个地方都出现空白。
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 30 // 设置分区顶部高度,cell分区顶部的空白
}
else {
return CGFloat.leastNonzeroMagnitude // 设置分区顶部高度,cell分区顶部无空白
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 2 { // 设置顶部分区视图
let headerView = UIView.init()
headerView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 30)
return headerView
}
else {
return nil // 没有顶部分区设置为nil
}
}
同理,sectionFooter也是如此。
3.UICollectionView顶部空白的相关设置和方法
3.1影响UICollectionView顶部空白的因素
1.contentInsetAdjustmentBehavior或者automaticallyAdjustsScrollViewInsets属性的设置,同UIScrollView;
2.UICollectionView分区头部视图sectionHeader的设置;
3.2代码设置上述属性和方法
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 初始化sectionHeader
let headerView = AKPracticeHeaderCollectionReusableView.section(collectionView: collectionView, indexPath: indexPath)
headerView.timeTitle = self.workList?[indexPath.section].title
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return .zero // 设置sectionHeader的尺寸
}
4.UIScrollView、UICollectionView、UITableView影响顶部空白的其它因素
4.1UINavigationBar的透明度设置
当使用系统的UINavigationBar时,self.navigationController.navigationBar.translucent当这个属性设为false时,tableview会在上方留出64.f的高度给导航栏。
网友评论