自定义TableView发送参数inSwift

时间:2016-05-23 13:16:22

标签: swift uitableview

我是Swift编码的新手。我有Android的经验。所以我知道我怎么能这样做Andorid。就像下面一样;

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();
}

所以我可以使用MyUserProfileAdapter中的MyUserProfileFragment中的所有方法。 但我不能在Swift中这样做。在Swift我有;

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
    }
}

这些是我项目中非常简单的代码。如何在Swift中使用showDialog方法?

1 个答案:

答案 0 :(得分:2)

在ViewController中使用此方法:

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

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

MyCustomCell中使用此方法:

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