[英]how to reduce/remove the left/right hand margin in a grouped UITableView?
[英]How to set left and right margin for UITableView in Swift
我在我的 controller 中使用UITableView ,它顯示帶有一些信息(標題、副標題和圖像)的單元格。 我想為tableView添加一些填充,但我找不到正確的解決方案。 這是我的表格視圖代碼:
private let tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = .clear
tableView.separatorStyle = .none
tableView.allowsSelection = false
tableView.showsVerticalScrollIndicator = false
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableView.automaticDimension
return tableView
}()
在viewDidLoad()里面我為那個tableView設置了約束
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
現在我的觀點是這樣的:
現在,當我嘗試通過添加以下內容在tableView閉包中配置contentInset屬性時:
tableView.contentInset = .init(top: 0, left: 23.5, bottom: 0, right: -23.5)
如您所見,它僅在左側增加了空間,但是查看調試視圖層次結構,我可以說它將該contentView移到了右側(它仍然具有與其父視圖相同的寬度)
來自視圖調試器的信息。 表視圖:
<UITableView: 0x7fba82016000; frame = (0 0; 390 844); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x60000023de90>; layer = <CALayer: 0x600000c4b9e0>; contentOffset: {-23.333333333333332, -47}; contentSize: {390, 635.66666666666663}; adjustedContentInset: {47, 23.5, 34, -23.5}; dataSource: <Myapp.WelcomeViewController: 0x7fba81c08f60>>
和第一個單元格:
<UITableViewCellContentView: 0x7fba84021250; frame = (0 0; 390 87); gestureRecognizers = <NSArray: 0x6000002cf900>; layer = <CALayer: 0x600000c2b900>>
TableView與單元格具有相同的寬度(390 對 390)。 如何在tableView的左側和右側添加我的填充,而不對該tableView進行限制(我希望該區域也可以滾動)
您可以通過在單元格的contentView
上設置.layoutMargins
來執行此操作(在單元格 class 本身或在cellForRowAt
中:
cell.contentView.layoutMargins = .init(top: 0.0, left: 23.5, bottom: 0.0, right: 23.5)
或在表格視圖本身上:
override func viewDidLoad() {
super.viewDidLoad()
tableView.layoutMargins = .init(top: 0.0, left: 23.5, bottom: 0.0, right: 23.5)
// if you want the separator lines to follow the content width
tableView.separatorInset = tableView.layoutMargins
}
你可以試試這個:
在添加約束的同時添加常量
NSLayoutConstraint.activate([
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 20),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
嘗試這個
override var frame: CGRect {
get {
return super.frame
}
set (newFrame) {
var frame = newFrame
frame.origin.x += 10
frame.size.width -= 2 * 10
super.frame = frame
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.