Swift自定義TableView左滑刪除按鈕樣式
1. 效果圖
2. 實現(xiàn)過程
在tableView的layoutSubview中遍歷闽瓢,然后可以自定義一個按鈕添加上去
override func layoutSubviews() {
super.layoutSubviews()
if #available(iOS 11.0, *) {
for subview in self.subviews where subview.isKind(of: NSClassFromString("UISwipeActionPullView")!) {
subview.backgroundColor = Main_RedColor
for view in subview.subviews where view.isKind(of: NSClassFromString("UISwipeActionStandardButton")!) {
view.backgroundColor = Main_RedColor
let deleteBtn = setupDeleteBtn(frame: CGRect(x: 0, y: 0, width: autoWidth(width: 160), height: view.height))
view.addSubview(deleteBtn)
view.bringSubview(toFront: deleteBtn)
}
}
} else { // IOS 10以及以下
for subview in subviews where subview.isKind(of: NSClassFromString("UITableViewCellDeleteConfirmationView")!) {
subview.backgroundColor = Main_RedColor
for view in subview.subviews where view.isKind(of: UIButton.self) {
view.backgroundColor = Main_RedColor
let deleteBtn = setupDeleteBtn(frame: view.frame)
view.addSubview(deleteBtn)
view.bringSubview(toFront: deleteBtn)
}
}
}
}
private func setupDeleteBtn(frame: CGRect) -> UIButton {
let deleteBtn = UIButton(type: .custom)
deleteBtn.frame = frame
deleteBtn.backgroundColor = Main_RedColor
deleteBtn.setTitle("刪除", for: .normal)
deleteBtn.setTitleColor(UIColor.white, for: .normal)
deleteBtn.titleLabel?.font = UIFont.systemFont(ofSize: autoFont(size: 32))
deleteBtn.setImage(UIImage(named: "delete"), for: .normal)
deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, autoWidth(width: 16))
return deleteBtn
}
3. 左滑功能
//MARK:- 左滑刪除
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
deleteItemByModel(chapter: chapterModels?[indexPath.row])
}