Swift自定义NSTableView中如何实现文本垂直居中对齐?
解决NSTableView单元格文本紧贴顶部的格式问题
你的问题核心在于手动使用frame布局文本框时未设置垂直对齐与间距,即便改用NSTableCellView,文本框依然从(0,0)位置开始布局,导致紧贴顶部。以下是具体修复方案:
1. 调整文本框内部对齐与内边距
如果CustomTextField是NSTextField的子类,在其SetTextAttributes方法中添加垂直居中与内边距设置,从文本框内部解决对齐问题:
func SetTextAttributes(row: Int, column: NSTableColumn, numberOfRows: Int) { // 保留你原有的属性设置(如字体、颜色等) // 设置文本垂直居中 self.alignment = .centerVertical // 为文本添加内边距,避免紧贴边框 if let textCell = self.cell as? NSTextFieldCell { textCell.contentInsets = NSEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) } }
2. 改用自动布局约束管理文本框位置
在CustomTableCellView的Setup方法中,放弃frame布局,使用自动布局约束让文本框在cell内垂直居中并保留上下间距:
func Setup(rectWidth: CGFloat, row: Int, column: NSTableColumn, numberOfRows: Int) { self.autoresizingMask = [.width, .height] let customTextField = CustomTextField() customTextField.translatesAutoresizingMaskIntoConstraints = false // 禁用自动转换约束 customTextField.SetTextAttributes(row: row, column: column, numberOfRows: numberOfRows) self.textField = customTextField self.addSubview(customTextField) // 添加约束:文本框左右填满cell,上下保留4pt间距(可根据需求调整) NSLayoutConstraint.activate([ customTextField.leadingAnchor.constraint(equalTo: self.leadingAnchor), customTextField.trailingAnchor.constraint(equalTo: self.trailingAnchor), customTextField.topAnchor.constraint(equalTo: self.topAnchor, constant: 4), customTextField.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -4) ]) }
3. 优化TableView的cell复用(可选但推荐)
当前代码每次创建新的CustomTableCellView,建议改用TableView的复用机制提升性能:
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let identifier = NSUserInterfaceItemIdentifier(rawValue: "CustomTableCell") // 尝试复用cell guard let dataCell = tableView.makeView(withIdentifier: identifier, owner: self) as? CustomTableCellView else { let newCell = CustomTableCellView() newCell.identifier = identifier return newCell } let width: CGFloat switch tableColumn?.identifier.rawValue { case "fund": width = 100.0 dataCell.textField?.stringValue = closingValues[row].fundName case "date": width = 120.0 dataCell.textField?.stringValue = SQLDateFormatter.string(from: closingValues[row].timeStamp) default: width = 100.0 dataCell.textField?.stringValue = String(format: "$%.2f", closingValues[row].close) } dataCell.Setup(rectWidth: width, row: row, column: tableColumn!, numberOfRows: closingValues.count) return dataCell }
完成以上修改后,单元格内的文本会自动垂直居中,且与边框保留合适间距,解决紧贴顶部的问题。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

