你需要什麼叫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的代表),「嗨,調用我們之前寫在你的body中的委託方法,我馬上向你發送參數」。你的VC採用這些參數,並在那個時候做你想做的任何事情。
對於Swift
:
首先,你TableViewCell.swift
文件,創建一個這樣的協議:
@class_protocol protocol ContactCellDelegate {
func didMoveSliderWithValue(value: Float)
}
現在,在你的手機類,創建一個代表屬性,如:
var cellDelegate: ContactCellDelegate?
在你的滑塊IBAction爲,調用委託方法是這樣的:
self.cellDelegate?.didMoveSliderWithValue(slider.value)
在你的VC做這些改變:
使其符合委託:
class MyTableViewController: UIViewController, ContactCellDelegate
返回之前添加此行cell in cellForRowAtIndexPath
cell.cellDelegate = self //Dont forget to make it conform to the delegate method
添加需要的delega的實現TE方法:
func didMoveSliderWithValue(value:float) {
//do what you want
}
我一直雨燕部分精確和總結,因爲它應該是很容易改變的具體對象 - 解釋迅速執行。但是,如果您對上述任何指針感到困惑,請發表評論。
另請參閱:StackOverflow answer on using Delegate pattern to pass data back
使用委託來實現。 –
什麼需要成爲什麼(請)的代表? – Jamie
創建您單元格的委託方法。讓你的VC委託該單元格。現在通過改變滑塊的值IBAction,調用委託方法並將值作爲參數傳遞。您的TableVC將會收到您的滑塊的值。你可以學習如何創建委託和委託模式[這裏](http://www.tutorialspoint.com/ios/ios_delegates.htm) – NSNoob