swift - Swift 中的自定义 TableView 发送参数

标签 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 方法?

最佳答案

在 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)

关于swift - Swift 中的自定义 TableView 发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37392059/

相关文章:

swift - VStack 中意外的 GeometryReader View 行为

ios - Swift 中的印地语数字集整数值

ios - 带有 SubView 的 tableView 的容器 View 或 UIViewController

iphone - 在 cellForRowInIndexPath 中创建数组

ios - 具有给定字体的 2 行 UILabel 的高度

ios - iOS 上可以使用相机追踪脸部吗?

objective-c - parse.com 云编码从 Objective C 到 Swift 的转换

ios - 设置嵌入 UITableViewCell 中的 UICollectionView

objective-c - ios 4.3 UITableView/UITableViewCell w/自定义背景在删除时不重绘

ios - UITableViewCell 高度错误