ios 向左滑动时在 UITableViewCell 中自定义编辑视图。Objective-C 或 Swift
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19164188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom edit view in UITableViewCell while swipe left. Objective-C or Swift
提问by ugoarangino
How to make a custom edit view in iOS7 UITableView with Objective C like the Evernote or the Apple Reminders app while swipe left. I have tried to set an custom editingAccessoryView, but this didn't work.
如何使用 Objective C 在 iOS7 UITableView 中创建自定义编辑视图,如向左滑动时的 Evernote 或 Apple Reminders 应用程序。我试图设置一个自定义的editingAccessoryView,但这没有用。
Evernote edit view:
印象笔记编辑视图:
Reminders edit view:
提醒编辑视图:
My current code is
我目前的代码是
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(@"delete");
}
}
I have tried to solve the problem with: (UITableViewController.h)
我试图解决这个问题:(UITableViewController.h)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//make cell
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[view setBackgroundColor:[UIColor greenColor]];
//add Buttons to view
cell.editingAccessoryView = view;
return cell;
}
And the same with: (UITableViewCell)
与: (UITableViewCell) 相同
- (void)willTransitionToState:(UITableViewCellStateMask)state;
- (void)setEditing:(BOOL)editing animated:(BOOL)animated;
- (UIView*)editingAccessoryView;
回答by Kartik 123
Just copy paste the code below!
只需复制粘贴下面的代码!
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Clona" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
//insert your editAction here
}];
editAction.backgroundColor = [UIColor blueColor];
UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath){
//insert your deleteAction here
}];
deleteAction.backgroundColor = [UIColor redColor];
return @[deleteAction,editAction];
}
回答by MattyG
Swift 3
斯威夫特 3
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .normal, title: "Edit") { (rowAction, indexPath) in
//TODO: edit the row at indexPath here
}
editAction.backgroundColor = .blue
let deleteAction = UITableViewRowAction(style: .normal, title: "Delete") { (rowAction, indexPath) in
//TODO: Delete the row at indexPath here
}
deleteAction.backgroundColor = .red
return [editAction,deleteAction]
}
Swift 2.1
斯威夫特 2.1
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .Normal, title: "Edit") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//TODO: edit the row at indexPath here
}
editAction.backgroundColor = UIColor.blueColor()
let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete") { (rowAction:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//TODO: Delete the row at indexPath here
}
deleteAction.backgroundColor = UIColor.redColor()
return [editAction,deleteAction]
}
Note: for iOS 8 onwards
注意:iOS 8 以上
回答by Ryan
You can use UITableViewRowAction
's backgroundColor
to set custom image or view. The trick is using UIColor(patternImage:)
.
您可以使用UITableViewRowAction
'sbackgroundColor
来设置自定义图像或视图。诀窍是使用UIColor(patternImage:)
.
Basically the width of UITableViewRowAction
area is decided by its title, so you can find a exact length of title(or whitespace) and set the exact size of image with patternImage
.
基本上UITableViewRowAction
区域的宽度由其标题决定,因此您可以找到标题(或空白)的确切长度并使用patternImage
.
To implement this, I made a UIView
's extension method.
为了实现这一点,我制作了 aUIView
的扩展方法。
func image() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
guard let context = UIGraphicsGetCurrentContext() else {
return UIImage()
}
layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
and to make a string with whitespace and exact length,
并制作一个带有空格和精确长度的字符串,
fileprivate func whitespaceString(font: UIFont = UIFont.systemFont(ofSize: 15), width: CGFloat) -> String {
let kPadding: CGFloat = 20
let mutable = NSMutableString(string: "")
let attribute = [NSFontAttributeName: font]
while mutable.size(attributes: attribute).width < width - (2 * kPadding) {
mutable.append(" ")
}
return mutable as String
}
and now, you can create UITableViewRowAction
.
现在,您可以创建UITableViewRowAction
.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let whitespace = whitespaceString(width: kCellActionWidth)
let deleteAction = UITableViewRowAction(style: .`default`, title: whitespace) { (action, indexPath) in
// do whatever you want
}
// create a color from patter image and set the color as a background color of action
let kActionImageSize: CGFloat = 34
let view = UIView(frame: CGRect(x: 0, y: 0, width: kCellActionWidth, height: kCellHeight))
view.backgroundColor = UIColor.white
let imageView = UIImageView(frame: CGRect(x: (kCellActionWidth - kActionImageSize) / 2,
y: (kCellHeight - kActionImageSize) / 2,
width: 34,
height: 34))
imageView.image = UIImage(named: "x")
view.addSubview(imageView)
let image = view.image()
deleteAction.backgroundColor = UIColor(patternImage: image)
return [deleteAction]
}
The result will look like this.
结果看起来像这样。
Another way to do this is to import custom font which has the image you want to use as a font and use UIButton.appearance
. However this will affect other buttons unless you manually set other button's font.
另一种方法是导入自定义字体,其中包含要用作字体的图像并使用UIButton.appearance
. 但是,除非您手动设置其他按钮的字体,否则这会影响其他按钮。
From iOS 11, it will show this message [TableView] Setting a pattern color as backgroundColor of UITableViewRowAction is no longer supported.
. Currently it is still working, but it wouldn't work in the future update.
从 iOS 11 开始,它将显示此消息[TableView] Setting a pattern color as backgroundColor of UITableViewRowAction is no longer supported.
。目前它仍在工作,但在未来的更新中将无法工作。
==========================================
==========================================
For iOS 11+, you can use:
对于 iOS 11+,您可以使用:
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .normal, title: "Delete") { (action, view, completion) in
// Perform your action here
completion(true)
}
let muteAction = UIContextualAction(style: .normal, title: "Mute") { (action, view, completion) in
// Perform your action here
completion(true)
}
deleteAction.image = UIImage(named: "icon.png")
deleteAction.backgroundColor = UIColor.red
return UISwipeActionsConfiguration(actions: [deleteAction, muteAction])
}
回答by Ram S
Refer this link : https://github.com/TeehanLax/UITableViewCell-Swipe-for-Options
请参阅此链接:https: //github.com/TeehanLax/UITableViewCell-Swipe-for-Options
And customize your uitableviewcell with multiple button.
并使用多个按钮自定义您的 uitableviewcell。
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
scrollView.contentSize = CGSizeMake(CGRectGetWidth(self.bounds) + kCatchWidth, CGRectGetHeight(self.bounds));
scrollView.delegate = self;
scrollView.showsHorizontalScrollIndicator = NO;
[self.contentView addSubview:scrollView];
self.scrollView = scrollView;
UIView *scrollViewButtonView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.bounds) - kCatchWidth, 0, kCatchWidth, CGRectGetHeight(self.bounds))];
self.scrollViewButtonView = scrollViewButtonView;
[self.scrollView addSubview:scrollViewButtonView];
// Set up our two buttons
UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
moreButton.backgroundColor = [UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0f];
moreButton.frame = CGRectMake(0, 0, kCatchWidth / 3.0f, CGRectGetHeight(self.bounds));
[moreButton setTitle:@"More" forState:UIControlStateNormal];
[moreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[moreButton addTarget:self action:@selector(userPressedMoreButton:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollViewButtonView addSubview:moreButton];
UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
shareButton.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:1.0f alpha:1.0f];
shareButton.frame = CGRectMake(kCatchWidth / 3.0f, 0, kCatchWidth / 3.0f, CGRectGetHeight(self.bounds));
[shareButton setTitle:@"Share" forState:UIControlStateNormal];
[shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[shareButton addTarget:self action:@selector(userPressedMoreButton:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollViewButtonView addSubview:shareButton];
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.backgroundColor = [UIColor colorWithRed:1.0f green:0.231f blue:0.188f alpha:1.0f];
deleteButton.frame = CGRectMake(kCatchWidth / 3.0f+kCatchWidth / 3.0f, 0, kCatchWidth / 3.0f, CGRectGetHeight(self.bounds));
[deleteButton setTitle:@"Delete" forState:UIControlStateNormal];
[deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[deleteButton addTarget:self action:@selector(userPressedDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollViewButtonView addSubview:deleteButton];
UIView *scrollViewContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))];
scrollViewContentView.backgroundColor = [UIColor whiteColor];
[self.scrollView addSubview:scrollViewContentView];
self.scrollViewContentView = scrollViewContentView;
UILabel *scrollViewLabel = [[UILabel alloc] initWithFrame:CGRectInset(self.scrollViewContentView.bounds, 10, 0)];
self.scrollViewLabel = scrollViewLabel;
[self.scrollViewContentView addSubview:scrollViewLabel];
I have implemented this code with my app got such result. You can add number of button in swipe cell.
Here is implemented screen shots
After swipe the cell 3 buttons appears "More","Share","Delete".
我已经用我的应用程序实现了这个代码得到了这样的结果。您可以在滑动单元格中添加按钮数量。
这是实现的屏幕截图
滑动后,单元格 3 按钮出现“更多”、“共享”、“删除”。
回答by SWAMY CHUNCHU
You Can try this,
你可以试试这个
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let backView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
backView.backgroundColor = #colorLiteral(red: 0.933103919, green: 0.08461549133, blue: 0.0839477703, alpha: 1)
let myImage = UIImageView(frame: CGRect(x: 30, y: backView.frame.size.height/2-14, width: 16, height: 16))
myImage.image = #imageLiteral(resourceName: "rubbish-bin")
backView.addSubview(myImage)
let label = UILabel(frame: CGRect(x: 0, y: myImage.frame.origin.y+14, width: 80, height: 25))
label.text = "Remove"
label.textAlignment = .center
label.textColor = UIColor.white
label.font = UIFont(name: label.font.fontName, size: 14)
backView.addSubview(label)
let imgSize: CGSize = tableView.frame.size
UIGraphicsBeginImageContextWithOptions(imgSize, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
backView.layer.render(in: context!)
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let delete = UITableViewRowAction(style: .destructive, title: " ") { (action, indexPath) in
print("Delete")
}
delete.backgroundColor = UIColor(patternImage: newImage)
return [delete, share]
}
回答by Vinay Kharb
This has support for both title and image.
这支持标题和图像。
For iOS 11 and afterwards:
对于 iOS 11 及更高版本:
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(
style: .normal,
title: "My Title",
handler: { (action, view, completion) in
//do what you want here
completion(true)
})
action.image = UIImage(named: "My Image")
action.backgroundColor = .red
let configuration = UISwipeActionsConfiguration(actions: [action])
configuration.performsFirstActionWithFullSwipe = false
return configuration
}
Also, similar method is available for leadingSwipeActions
此外,类似的方法可用于 leadingSwipeActions
Source:
来源:
https://developer.apple.com/videos/play/wwdc2017/201/(Talks about this at around 16 mins time) https://developer.apple.com/videos/play/wwdc2017/204/(Talks about this at around 23 mins time)
https://developer.apple.com/videos/play/wwdc2017/201/(在大约 16 分钟的时间谈论这个) https://developer.apple.com/videos/play/wwdc2017/204/(谈论这个在大约 23 分钟的时间)
回答by S.Govind
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// action one
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
print("Edit tapped")
self.myArray.add(indexPath.row)
})
editAction.backgroundColor = UIColor.blue
// action two
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
print("Delete tapped")
self.myArray.removeObject(at: indexPath.row)
self.myTableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
})
deleteAction.backgroundColor = UIColor.red
// action three
let shareAction = UITableViewRowAction(style: .default, title: "Share", handler: { (action , indexPath)in
print("Share Tapped")
})
shareAction.backgroundColor = UIColor .green
return [editAction, deleteAction, shareAction]
}
回答by CodeCracker
If you want to use only text while making swipe actions then you can use iOS default swipe actions but if you want image and text, then you have to customize it. I have found a great tutorial and sample that can resolve this problem.
如果您只想在执行滑动操作时使用文本,那么您可以使用 iOS 默认的滑动操作,但如果您想要图像和文本,则必须对其进行自定义。我找到了一个很好的教程和示例,可以解决这个问题。
Try out this repository to get the custom swipe cell. You can add multiple option here.
试试这个存储库以获得自定义滑动单元。您可以在此处添加多个选项。
http://iosbucket.blogspot.in/2016/04/custom-swipe-table-view-cell_16.html
http://iosbucket.blogspot.in/2016/04/custom-swipe-table-view-cell_16.html
https://github.com/pradeep7may/PKSwipeTableViewCell
回答by MacInnis
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .Destructive, title: "Delete") { (action, indexPath) in
// delete item at indexPath
}
let share = UITableViewRowAction(style: .Normal, title: "Disable") { (action, indexPath) in
// share item at indexPath
}
share.backgroundColor = UIColor.blueColor()
return [delete, share]
}
The above code shows how to create to custom buttons when your swipe on the row.
上面的代码显示了在行上滑动时如何创建自定义按钮。
回答by Ilya Ilin
As I think, It's not best way to using UIGestureRecognizer-based cells.
我认为,这不是使用基于 UIGestureRecognizer 的单元格的最佳方式。
First, you'll not have any options to use CoreGraphics.
首先,您没有任何选项可以使用 CoreGraphics。
Perfect solution, will UIResponderor one UIGestureRecognizer
for whole table view. Not for every UITableViewCell
. It will make you app stuck.
完美的解决方案,将UIResponder或一个UIGestureRecognizer
用于整个表视图。不是每个UITableViewCell
. 它会让你的应用程序卡住。