Aybuke Aybuke - 6 months ago 18
Swift Question

Custom TableView send parameter inSwift

I'm very new in Swift coding. I have experience in Android. So I know how can I do this is Andorid. It is like below;

public class MyUserProfileFragment extends BaseFragment {
MyUserProfileAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new MyUserProfileAdapter(MyUserProfileFragment.this, getActivity());
}
public showDialog(){
//do something
}
}

public class MyUserProfileAdapter extends BaseAdapter {
MyUserProfileFragment fragmentMyUserProfile;
Context context;
public MyUserProfileAdapter(MyUserProfileFragment fragment, Context context) {
this.context = context;
LayoutInflater layoutInflater = LayoutInflater.from(context);
this.fragmentMyUserProfile = fragment;
}
fragmentMyUserProfile.showDialog();
}


So i can use all methods in MyUserProfileFragment from MyUserProfileAdapter.
But I can't do this in Swift. In Swift I have ;

class ViewControllerNewGame: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! MyCustomCell
return cell
}
func showDialog(){
//some actions
}
}

class MyCustomCell: UITableViewCell {
@IBOutlet weak var img1: UIButton!
@IBAction func click(sender: UIButton) {
//I want to use showDialog method from ViewVoncontroller
}
}


Those are very simle codes from my project. How can I use showDialog method in Swift?

Answer

Use this method in ViewController :

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewControllerNewGame.click(_:)),name:"click", object: nil)

func show(notification: NSNotification) {
        ViewControllerNewGame.click()
}

And use this method in MyCustomCell :

NSNotificationCenter.defaultCenter().postNotificationName("click", object: nil)
Comments