你需要的是Delegate Pattern。
从那里引用来解释它的含义:
委托是一种简单而强大的模式,其中一个对象在一个
程序代表另一个对象或与另一个对象协调。
委托对象保持对另一个对象的引用——
委托——并在适当的时候向它发送消息。这
消息通知委托对象委托的事件是
即将处理或刚刚处理。代表可以回应
通过更新自身或其他对象的外观或状态来发送消息
在应用程序中,在某些情况下它可以返回一个值
影响即将发生的事件的处理方式。的主要价值
委托是它允许您轻松自定义行为
一个中心对象中的多个对象。
这些图表将帮助您了解发生了什么:
架构:
操作:
现在至于如何实现它,这是你必须做的。
对于Objective-C:
首先,创建UITableViewCell 的委托方法。让我们将其命名为ContactTableViewCell。
在您的 ContactTableViewCell.h 文件中,执行以下操作:
@protocol ContactCellDelegate <NSObject>
@required
-(void) didMoveSliderWithValue:(float) value;
@end
@interface ContactTableViewCell : UITableViewCell
@property (weak, nonatomic) id<ContactCellDelegate> delegate;
现在让你的 TableViewController 符合这个委托。让我们将您的 VC 命名为MyTableViewController。
在MyTableViewController.h,执行此操作:
@interface MyTableViewController : UIViewController <ContactCellDelegate> //Use UITableViewController if you are using that instead of UIViewController.
在您的cellForRowAtIndexPath 中,在返回单元格之前,添加以下行:
cell.delegate = self;
在MyTableViewController.m 内添加委托方法的实现。
-(void) didMoveSliderWithValue: (float) value
{
NSLog(@"Value is : %f",value);
//Do whatever you need to do with the value after receiving it in your VC
}
现在让我们回到您的ContactTableViewCell.m。在该文件中,您必须添加一些 IBAction 以捕获滑块中的值更改事件。假设它是以下内容:
- (IBAction)sliderValueChanged:(UISlider *)sender {
self.myTextLabel.text = [@((int)sender.value) stringValue]; //Do whatever you need to do in cell.
//Now call delegate method which will send value to your view controller:
[delegate didMoveSliderWithValue:sender.value];
}
当您调用委托方法时,它将运行我们之前在MyTableViewController 中编写的实现。在该方法中做任何你需要的事情。
这里发生的情况是,您的 Cell 将消息发送到您想要的 VC(它是 Cell 的委托),即“嘿,调用我们之前在您的正文中编写的委托方法。我正在向您发送参数” .您的 VC 获取参数并在当时使用该信息执行您希望它执行的任何操作。
对于Swift:
首先,你的TableViewCell.swift 文件,创建一个像这样的协议:
@class_protocol protocol ContactCellDelegate {
func didMoveSliderWithValue(value: Float)
}
现在在您的 Cell 类中,创建一个委托属性,例如:
var cellDelegate: ContactCellDelegate?
在您的 Slider IBAction 中,像这样调用委托方法:
self.cellDelegate?.didMoveSliderWithValue(slider.value)
在您的 VC 中进行以下更改:
使其符合委托:
class MyTableViewController: UIViewController, ContactCellDelegate
在cellForRowAtIndexPath中返回单元格之前添加此行
cell.cellDelegate = self //Dont forget to make it conform to the delegate method
添加所需委托方法的实现:
func didMoveSliderWithValue(value:float) {
//do what you want
}
我对 Swift 部分进行了精确和总结,因为将详细的 Obj-C 解释更改为 Swift 实现应该很容易。但是,如果您对上述任何指示感到困惑,请发表评论。
另见:StackOverflow answer on using Delegate pattern to pass data back