2016-02-19 4 views
0

В настоящее время я пытаюсь создать представление вложенного списка в iOS, эта таблица будет похожа на p-список, что означает каждый раз, когда пользователи нажимают знак «плюс» в начале каждой ячейки , под ним появятся новые строки.Техника для вставки новой строки в UITableView

На данный момент я думаю, что решение будет: при нажатии на кнопку обновить источник данных таблицы, а затем вставить новые строки под индексом щелчка (вот где я застрял!).

оригинальный источник данных является массивом строки: { «а», «б», «в», «г»}

Данные, которые добавлены после каждой записи: { "суб-1 "," sub-2 "," sub-3 "}

Я пишу эту демонстрацию на C#, но я могу понять swift и obj-c, так что не стесняйтесь публиковать любой язык, который вам нравится!

Мой код в настоящее время включают в себя 3 основных класса: CustomtableSource.csCustomTableViewCell.cs и ExpandableListViewController.cs

CustomTableSource.cs:

class CustomTableSource : UITableViewSource 
{ 
    private List<Book> _books; 
    string CellIdentifier = "TableCell";    

    public CustomTableSource(List<Book> books) 
    { 
     _books = books;    
    } 

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) 
    { 
     var customCell = tableView.DequeueReusableCell(CellIdentifier) as CustomTableViewCell;    
     Book book = _books[indexPath.Row]; 
     UIImage img = UIImage.FromFile("Images/closed.png"); 

     if (customCell == null) 
     { 
      customCell = new CustomTableViewCell(CellIdentifier); 
      customCell.UpdateCell(book.BookTitle, img); 
     } 

     return customCell; 
    } 

    public override nint RowsInSection(UITableView tableview, nint rowInSection) 
    { 
     return _books.Count; 
    } 

    public override nint NumberOfSections(UITableView tableView) 
    { 
     return 1; 
    }   
} 

CustomTableViewCell.cs

public class CustomTableViewCell : UITableViewCell 
{ 
    private UIButton _button;// = UIButton.FromType(UIButtonType.Custom); 
    private UILabel _title; 

    public CustomTableViewCell(string cellId) : base (UITableViewCellStyle.Default, cellId) 
    { 
     SelectionStyle = UITableViewCellSelectionStyle.Gray; 
     ContentView.BackgroundColor = UIColor.Clear; 

     _button = UIButton.FromType(UIButtonType.Custom); 
     /* _button.TouchUpInside += (sender, args) => 
     { 
      _button.SetImage(UIImage.FromFile("Images/open.png"), UIControlState.Normal); 

     };*/ 
     _title = new UILabel(); 
     _title.BackgroundColor = UIColor.Clear; 

     ContentView.AddSubviews(new UIView[] {_button, _title}); 
    } 

    public void UpdateCell(string title, UIImage image) 
    { 
     _button.SetImage(image, UIControlState.Normal); 
     _title.Text = title; 
    } 

    public override void LayoutSubviews() 
    { 
     base.LayoutSubviews(); 
     _button.Frame = new CGRect(12, 22, 10, 10); 
     _title.Frame = new CGRect(30, 5, ContentView.Bounds.Width, ContentView.Bounds.Height); 
    } 
} 

ExpandableListViewController.cs:

public class ExpandableListViewController : UIViewController 
{ 
    private UITableView _tableView; 
    private UIButton _rowButton; 

    public ExpandableListViewController() : base("ExpandableListViewController", null) 
    {       
    } 

    public override void ViewDidLoad() 
    { 
     base.ViewDidLoad(); 
     var width = View.Bounds.Width; 
     var height = View.Bounds.Height; 
     _tableView = new UITableView(new CGRect(0, 0, width, height)); 
     //_rowButton = CustomTableViewCell._button;    

     _tableView.AutoresizingMask = UIViewAutoresizing.All; 

     List<Book> books = new List<Book>(); 
     books.Add(new Book() { BookTitle = "C programming", Level = 0 }); 
     books.Add(new Book() { BookTitle = "Beginner", Level = 1 }); 
     books.Add(new Book() { BookTitle = "Moderate", Level = 1 }); 
     books.Add(new Book() { BookTitle = "Advanced", Level = 1 }); 
     books.Add(new Book() { BookTitle = "Java programming", Level = 2 }); 
     books.Add(new Book() { BookTitle = "Basic", Level = 1 }); 
     books.Add(new Book() { BookTitle = "Java Swing", Level = 1 }); 
     books.Add(new Book() { BookTitle = "Pascal programming", Level = 0 }); 
     //books.Add(new Book() { BookTitle = "CoBol programming", Level = 0 }); 

     CustomTableSource tableSource = new CustomTableSource(books); 

     _tableView.Source = tableSource; 
     Add(_tableView); 

     /*_rowButton.TouchUpInside += (sender, args) => 
     { 
      _rowButton.SetImage(UIImage.FromFile("Images/open.png"), UIControlState.Normal); 
      _tableView.BeginUpdates(); 
      books.Add(new Book() { BookTitle = "CoBol programming", Level = 0 }); 
      _tableView.ReloadData();     
      _tableView.EndUpdates(); 
     };*/ 
    } 
} 

скриншота того, что я сделал:

enter image description here

+0

Вот сообщение в блоге об этом: http://www.appcoda.com/expandable- table-view/ – jasonnoahchoi

+0

Спасибо за предложение. Любой более близкий пример моей проблемы? –

ответ

0

Добавить этот код CustomTableSource.cs, чтобы вызвать событие, когда пользователь выбирает строку.

public event EventHandler<int> OnRowItemSelected; 

public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath) 
{ 
    if (OnRowItemSelected != null) 
    { 
     OnRowItemSelected(tableView, indexPath.Row); 
    } 
    tableView.DeselectRow(indexPath, true); 
} 

Из ExpandableListViewController.cs, подписываться грести выбранное событие, добавить новую книгу, когда он поднял и перезагрузить таблицу затем

tableSource. OnRowItemSelected += (s, e) => { 
    //Insert new sub item list 
    books.Insert(e, new Book { /*init*/ }); 

    //reload table 
    _tableView.ReloadData(); 
};