2013-02-10 4 views
0

Я пытаюсь добавить UISwitch в каждую ячейку (это работает). Когда я нажимаю, чтобы переключить любой переключатель, кроме последнего, все они дают последний переключатели состояния, пока не измените последние переключатели государствуТолько последний UISwitch в UITableViewCell запускает

 `public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { 
      //---- declare vars 
      UITableViewCell cell = tableView.DequeueReusableCell (this._cellIdentifier); 

      //---- if there are no cells to reuse, create a new one 
      if (cell == null) { 
       // This changes the style of the UITableViewCell to the Default style 
       cell = new UITableViewCell (UITableViewCellStyle.Default, this._cellIdentifier); 

       // Instantiate a cell accessory here 
       uiSwitch = new UISwitch (new RectangleF (0f, 0f, 20f, 20f)); 
       uiSwitch.Tag = indexPath.Row; 
       uiSwitch.ValueChanged += (object sender, EventArgs e) => { 
        Console.WriteLine ("Cell Switch value is now {0}", uiSwitch.On); 
       }; 
       _vRMs.View.AddSubview (uiSwitch); 

       // keep a reference to each cell you create, 
       // e.g. add them to a static List<UITableViewCell>. 
       // The GC won't be able to collect them so the event handler will work later. 
       cells.Add (cell); 
      } 

      //---- create a shortcut to our item 
      TableViewItem item = this._TableViewItemGroupList[indexPath.Section].Items[indexPath.Row]; 

      cell.TextLabel.Text = item.Name; 
      cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; 
      cell.AccessoryView = uiSwitch; 
      // cell.DetailTextLabel.Text = item.SubHeading; 


      return cell; 
     }` 

Я хотел бы знать, если весь этот код необходимо создать таблицу с UISwitches - новичок в мире iPhone dev, я не уверен. Я надеюсь, что это обновление поможет мне.

`using System; 
using System.Drawing; 
using System.Collections.Generic; 

using MonoTouch.Foundation; 
using MonoTouch.UIKit; 

namespace eOneRaw { 
    public partial class vRMs : UIViewController { 

     #region FIELDS 
     private string _ViewTitle = "RMs"; 
     private UITableView _TableView; 
     private TableViewDataSource _TableViewDataSource; 
     private List<TableViewItemGroup> _TableViewItemGroupList; 
     private static vRMs _vRMs; 
     #endregion  

     #region PROPERTIES 
#endregion 

     #region ViewDidLoad 
     public override void ViewDidLoad() { 
      base.ViewDidLoad(); 

      // Title the Controller 
      Title = _ViewTitle; 

      #region UITableView Setup 
      // Set up the table and data 
      this.CreateTableItems(); 

      // Create the UITableView 
      _TableView = new UITableView() { 
       Delegate = new TableViewDelegate(_TableViewItemGroupList), 
       DataSource = _TableViewDataSource, 
       AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth, 
      }; 

      _TableView.SizeToFit(); 

      // Reposition and resize the receiver 
      _TableView.Frame = new RectangleF (0, 0, this.View.Frame.Width, this.View.Frame.Height); 

      // Add the table view as a subview 
      this.View.AddSubview(_TableView); 
#endregion 

      #region Define the Look of the View 
      var _barbtnCancel = new UIBarButtonItem(UIBarButtonSystemItem.Done); 
      NavigationItem.LeftBarButtonItem = _barbtnCancel; 

      _barbtnCancel.Clicked += (s, e) => { 
       this.NavigationController.PopViewControllerAnimated(true); 
      }; 
#endregion 

     } // end ViewDidLoad 
#endregion 

     #region METHODS 
     public vRMs() { 
      // Shouldn't ever happen 
      _vRMs = this; 
      Console.WriteLine (Environment.StackTrace); 
     } 

     public override void DidReceiveMemoryWarning() { 
      // Releases the view if it doesn't have a superview. 
      base.DidReceiveMemoryWarning(); 

      // Release any cached data, images, etc that aren't in use. 
     } 
#endregion 

     #region ALL TABLE FUNCTIONALITY 

     #region CreateTableItems 
     //======================================================================== 
     /// <summary> 
     /// Creates a set of table items. 
     /// </summary> 
     // This is where you define your table 
     protected void CreateTableItems() { 
      _TableViewItemGroupList = new List<TableViewItemGroup>(); 

      //---- declare vars 
      TableViewItemGroup tGroup; 

      tGroup = new TableViewItemGroup() { Name = "Regional Managers" }; 
      tGroup.Items.Add (new TableViewItem() { Name = "Chris" }); 
      tGroup.Items.Add (new TableViewItem() { Name = "Mike" }); 
      tGroup.Items.Add (new TableViewItem() { Name = "Dan" }); 
      tGroup.Items.Add (new TableViewItem() { Name = "Steve" }); 
      _TableViewItemGroupList.Add (tGroup); 

      this._TableViewDataSource = new TableViewDataSource(_TableViewItemGroupList); 
     } 
#endregion 

     #region CLASS TableViewDelegate 
     // The delegate manages the transitions from view-to-view 
     private class TableViewDelegate : UITableViewDelegate { 
      private List<TableViewItemGroup> _TableViewItemGroupList; 

      public TableViewDelegate(List<TableViewItemGroup> pList) { 
       this._TableViewItemGroupList = pList; 
      } 

      public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { 
       return; 
      } 
     } 
#endregion 

     #region CLASS TableViewDataSource 
     public class TableViewDataSource : UITableViewDataSource { 

      protected List<TableViewItemGroup> _TableViewItemGroupList; 
      string _cellIdentifier = "TableViewCell"; 
      private static UISwitch uiSwitch; 
      static List<UITableViewCell> cells = new List<UITableViewCell>(); 

      public TableViewDataSource (List<TableViewItemGroup> items) { 
       this._TableViewItemGroupList = items; 
      } 

      /// <summary> 
      /// Called by the TableView to determine how many sections(groups) there are. 
      /// </summary> 
      public override int NumberOfSections (UITableView tableView) { 
       return this._TableViewItemGroupList.Count; 
      } 

      /// <summary> 
      /// Called by the TableView to determine how many cells to create for that particular section. 
      /// </summary> 
      public override int RowsInSection (UITableView tableview, int section) { 
       return this._TableViewItemGroupList[section].Items.Count; 
      } 

      /// <summary> 
      /// Called by the TableView to retrieve the header text for the particular section(group) 
      /// </summary> 
      public override string TitleForHeader (UITableView tableView, int section) { 
       return this._TableViewItemGroupList[section].Name; 
      } 

      /// <summary> 
      /// Called by the TableView to retrieve the footer text for the particular section(group) 
      /// </summary> 
      public override string TitleForFooter (UITableView tableView, int section) { 
       return this._TableViewItemGroupList[section].Footer; 
      } 

      #region UITableViewCell 
      /// <summary> 
      /// Called by the TableView to get the actual UITableViewCell to render for the particular section and row 
      /// </summary> 
      public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { 
       //---- declare vars 
       UITableViewCell cell = tableView.DequeueReusableCell (this._cellIdentifier); 

       //---- if there are no cells to reuse, create a new one 
       if (cell == null) { 
        // This changes the style of the UITableViewCell to the Default style 
        cell = new UITableViewCell (UITableViewCellStyle.Default, this._cellIdentifier); 

        // This changes the style of the UITableViewCell to the Subtitle style, 
        // which displays a second line of text within the cell. 
        // cell = new UITableViewCell (UITableViewCellStyle.Subtitle, this._cellIdentifier); 

        // Instantiate a cell accessory here 
        uiSwitch = new UISwitch (new RectangleF (0f, 0f, 20f, 20f)); 
        uiSwitch.Tag = indexPath.Row; 
        uiSwitch.ValueChanged += (object sender, EventArgs e) => { 
         Console.WriteLine ("Cell Switch value is now {0}", uiSwitch.On); 
        }; 
        _vRMs.View.AddSubview (uiSwitch); 

        // keep a reference to each cell you create, 
        // e.g. add them to a static List<UITableViewCell>. 
        // The GC won't be able to collect them so the event handler will work later. 
        cells.Add (cell); 
       } 

       //---- create a shortcut to our item 
       TableViewItem item = this._TableViewItemGroupList[indexPath.Section].Items[indexPath.Row]; 

       cell.TextLabel.Text = item.Name; 
       cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; 
       cell.AccessoryView = uiSwitch; 
       // cell.DetailTextLabel.Text = item.SubHeading; 

       // Add an image if needed 
       /* 
       if(!string.IsNullOrEmpty(item.ImageName)) 
       { 
        cell.ImageView.Image = UIImage.FromFile("Images/" + item.ImageName); 
       } 
       */ 

       return cell; 
      } 
#endregion 
     } // end TableViewDataSource Class 
#endregion 

     #region CLASS TableViewItemGroup 
     //======================================================================== 
     /// <summary> 
     /// A group that contains table items 
     /// </summary> 
     public class TableViewItemGroup { 
      public string Name { get; set; } 
      public string Footer { get; set; } 

      public List<TableViewItem> Items { 
       get { return this._items; } 
       set { this._items = value; } 
      } 

      protected List<TableViewItem> _items = new List<TableViewItem>(); 

      public TableViewItemGroup() { 
      } 
     } 
#endregion 

     #region CLASS TableViewItem 
     //======================================================================== 
     /// <summary> 
     /// Represents our item in the table 
     /// </summary> 
     public class TableViewItem { 
      public string Name { get; set; } 
      public string SubHeading { get; set; } 
      public string ImageName { get; set; } 

      public TableViewItem() { 
      } 
     } 
#endregion 

#endregion 

     #region OBSOLETE methods 
     // ***************************** OBSOLETE 
     // ***************************** OBSOLETE 
     // ***************************** OBSOLETE 
     [Obsolete] 
     public override void ViewDidUnload() { 
      base.ViewDidUnload(); 

      // Clear any references to subviews of the main view in order to 
      // allow the Garbage Collector to collect them sooner. 
      // 
      // e.g. myOutlet.Dispose(); myOutlet = null; 

      ReleaseDesignerOutlets(); 
     } 

     [Obsolete] 
     public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { 
      // Return true for supported orientations 
      return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); 
     } 
#endregion 

    } 
}` 

ответ

1

С кодом возникает несколько проблем.

Во-первых, я думаю, что ваш образец кода пропустит жизненно важную часть?

Какова область действия переменной UISwitch? Кажется, это ссылка на уровне класса?


Во-вторых, я думаю, что ваш код не обрабатать повторного использования клеток очень хорошо - линия uiSwitch.Tag = indexPath.Row; не вызывается в случае повторного использования.


В-третьих, я не слишком уверен, что ваш подход действительно очень масштабируемым - хотя это будет работать для небольших списков


Во всех честно, вы, вероятно, лучше просто создавать пользовательские ячейка для этого переключателя - и затем, используя значения из этих пользовательских ячеек ... для того, чтобы создать пользовательскую ячейку, см:

+0

Благодарим вас за отзыв. Переменная UISwitch находится на уровне класса. Ты прав. Я не уверен, почему я использовал .tag. Наверное, я надеялся использовать это как индекс. Это небольшой список. Я просто не могу придумать, как заставить все UISwithes быть независимыми друг от друга. – Mike

1

В дополнение к проблемам, отметил Стюартом, другая проблема заключается в том, что вы рециркуляции клеток, так что вы могли бы в конечном итоге с переработанной ячейку, которая указывает на другое состояние, что вы хотели.

Для случая, подобного этому, вы можете просто использовать уникальный ключ для каждого созданного вами UISlider, чтобы вы никогда не повторно использовали UISlider для двух разных переменных. Кроме того, вам нужно изменить свой код, чтобы обработчик сообщал разные, основываясь на IndexPath, который действовал на нем.

+0

Я уверен, что вы слышите это все время - я ваш большой поклонник. Теперь, когда маленькая школьница вышла из меня, вы могли бы указать мне на какой-то код, который бы это сделал? В основном мои проблемы включают динамическое перемещение UISwitches в ячейки, а затем возможность ссылаться на эти ячейки «правильным образом». Я из C# ASP.net и среды Windows и думаю, что ожидаю что-то вроде ListBox, где есть ключ (скрытый для ссылки) и значение (отображается). Итак, какие-либо рекомендации? – Mike

+0

Большинство образцов используют построитель интерфейсов. Если вы также можете рекомендовать книгу, которая пишет чистый MonoTouch без Interface Builder, или даже лучше, напишите. – Mike

+0

Если это небольшой список, подумайте о том, чтобы провести список UISwitches отдельно для ячеек - посмотрите, как этот код работает в MonoTouch.Dialog - https://github.com/migueldeicaza/MonoTouch.Dialog/blob/master/MonoTouch.Dialog/Elements .cs # L260 – Stuart

Смежные вопросы