2013-02-10 43 views
0

我想在每個單元中添加一個UISwitch(這個工作)。當我點擊切換除最後一個以外的任何開關,他們都給予最後的開關狀態,直到我改變最後的開關狀態只有UITableViewCell中的最後一個UISwitch觸發

 `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開發者來說是新手,我不確定。 我希望這個更新將有助於我的事業。

`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 2013-02-12 18:04:50

1

除了問題由Stuart指出,另一個問題是,你正在回收的細胞,所以你可能最終與被指向另一個狀態的再生細胞, nto你想要的。

對於這種情況,您可以爲每個創建的UISlider使用一個唯一的鍵,以確保您永遠不會爲兩個不同的變量重用UISlider。或者,您需要更改您的代碼,以便處理程序根據對其執行操作的IndexPath來告訴它們。

+0

我確定你一直聽到這個 - 我是你的粉絲。 既然這個小女生不在我身邊,你能否指點我一些可以實現這一點的代碼?主要是我的問題是將UISwitches動態放入單元格中 - 然後才能夠以「正確的方式」引用這些單元格。 我來自C#ASP.net和Windows環境,並認爲我期待像一個列表框,其中有一個鍵 (隱藏引用)和值(顯示)。那麼,有什麼建議? – Mike 2013-02-12 18:32:06

+0

大多數樣本使用界面構建器。如果你也可以,或者推薦一本可以在沒有Interface Builder的情況下編寫純粹的MonoTouch的書 - 或者更好,請寫一篇。 – Mike 2013-02-12 19:01:20

+0

如果它是一個小列表,考慮將單獨的UISwitch列表保存到單元格中 - 請參閱此代碼在MonoTouch.Dialog中的工作方式 - https://github.com/migueldeicaza/MonoTouch.Dialog/blob/master/MonoTouch.Dialog/Elements .cs#L260 – Stuart 2013-02-12 19:13:43

相關問題