最近做項目有個需求是向左滑動cell出現刪除和分享按鈕,要求顯示圖片沒有文字。代碼:實現一下tableView.m (- (nullable NSArray)tableView:(UITableView )tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0) __TVOS_PROHIBITED; )
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
//UITableViewRowAction是iOS8才有的,title不想要打了空格占著大小
UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"? ? ? ? ? " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSLog(@"點擊刪除");
}];
UITableViewRowAction *shareRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"? ? ? ? ? " handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSLog(@"點擊分享");
}];
// 這個地方:先加入的在右邊
return @[shareRowAction, deleteRowAction];
}
cell.m (在- (void)layoutSubviews; 這個方法里做處理)
for (UIView *subView in self.subviews) {
if([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")]) {
// 拿到subView之后再獲取子控件
// 因為上面刪除按鈕是第二個加的所以下標是1
UIView *deleteConfirmationView = subView.subviews[1];
//改背景顏色
deleteConfirmationView.backgroundColor = [UIColor colorWithRed:204.0/255.0 green:42.0/255.0 blue:62.0/255.0 alpha:1.0];
for (UIView *deleteView in deleteConfirmationView.subviews) {
NSLog(@"%@",deleteConfirmationView.subviews);
UIImageView *deleteImage = [[UIImageView alloc] init];
deleteImage.contentMode = UIViewContentModeScaleAspectFit;
deleteImage.image = [UIImage imageNamed:delete];
deleteImage.frame = CGRectMake(0, 0, deleteView.frame.size.width, deleteView.frame.size.height);
[deleteView addSubview:deleteImage];
}
// 這里是右邊的
UIView *shareConfirmationView = subView.subviews[0];
shareConfirmationView.backgroundColor = [UIColor colorWithRed:142.0/255.0 green:201.0/255.0 blue:75.0/255.0 alpha:1.0];
for (UIView *shareView in shareConfirmationView.subviews) {
UIImageView *shareImage = [[UIImageView alloc] init];
shareImage.contentMode = UIViewContentModeScaleAspectFit;
shareImage.image = [UIImage imageNamed:share];
shareImage.frame = CGRectMake(0, 0, shareView.frame.size.width, shareView.frame.size.height);
[shareView addSubview:shareImage];
}
}
}
效果圖
WechatIMG53.jpeg
看圖層發現加了很多圖片的,因為layoutSubviews會調用多次,可以把控件懶加載就行了,或者其實UITableViewCellDeleteConfirmationView里的控件本質上是UIButton,直接設置圖片。