如何在tableview单元格中放置一个按钮?

时间:2016-06-23 11:26:29

标签: ios uitableview xamarin

我是新手,所以我遇到了麻烦。我的目标也就像标题所说的那样,是一个单元格内的按钮。如果你想看到我的代码,这可以帮助你回答这个问题,这里是代码:

using System;
using System.Collections.Generic;
using System.Text;
using Foundation;
using UIKit;

namespace TableView
{
public class TableSource : UITableViewSource
{
    string[] tableItems;
    string cellIdentifier = "TableCell"; 



    public TableSource (string[] items)
    {
        tableItems = items; 
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        return tableItems.Length; 
    }
    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        new UIAlertView("Alert", "You selected: " + tableItems[indexPath.Row], null, "Next Site", null).Show();
        tableView.DeselectRow(indexPath, true); 
    }
    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
        if (cell == null)
            cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier);
        cell.TextLabel.Text = tableItems[indexPath.Row];

        if(indexPath.Row > -1)
            cell.DetailTextLabel.Text = tableItems[indexPath.Row - 0];



            return cell; 
    }
}
}

如果需要,这是ViewController的代码。

2 个答案:

答案 0 :(得分:0)

首先,您需要在按钮上添加一个标记,以便您可以在 cellForRowAtIndexPath 函数中看到正在按下的按钮,如下所示:

cell.Button.tag = indexPath.row

然后在 IBAction 内,你可以看到按下这个按钮的确切位置:

@IBAction func buttonPressed(sender: AnyObject)
{
    let button = sender as! UIButton
    let index = NSIndexPath(forRow: button.tag, inSection: 0)
}

答案 1 :(得分:0)

创建自定义TableViewCell并在那里添加按钮。比在GetCell方法中使用自定义TableViewCell。

class MyButtonTableViewCell : UITableViewCell
{
    public UIButton MyButton { get; private set; }

    public MyButtonTableViewCell() : base(UITableViewCellStyle.Default, "MyButtonCell")
    {
        MyButton = new UIButton(UIButtonType.System);
        MyButton.Frame = ContentView.Bounds;
        MyButton.SetTitle("My Title", UIControlState.Normal);

        ContentView.AddSubview(MyButton);
    }
}


public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
    UITableViewCell cell = tableView.DequeueReusableCell("MyButtonCell");

    if (cell == null)
        cell = MyButtonTableViewCell();

        return cell; 
}
相关问题