【问题标题】:How do I put a button inside a tableview cell?如何在表格视图单元格中放置一个按钮?
【发布时间】:2016-06-23 11:26:29
【问题描述】:

我是新手,所以我很难做到这一点。就像标题所说的那样,我的目标太过分了,一个单元格内的按钮。如果你想看我的代码,这样可以帮助你回答这个问题,这里是代码:

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 的代码。

【问题讨论】:

  • 如果答案有问题,您可以将其删除或编辑。

标签: ios uitableview xamarin


【解决方案1】:

创建一个自定义 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; 
}

【讨论】:

  • 如何创建自定义 tableviewcell?我的意思是我可以把这段代码放在 tableviewsource 中吗?
  • 我的答案包含一个如何创建自定义单元格的示例。请参见 MyButtonTableViewCell 类。您可以将该类放在 TableViewSource 中。
  • 如果我的答案符合您的需要,我希望看到它标记在正确答案上。 :-)
  • 对不起,我忘记了,哈哈:)
【解决方案2】:

首先你需要给按钮添加一个标签,这样你就可以看到在 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)
}

【讨论】:

    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2014-02-01
    相关资源
    最近更新 更多