Switching to different UITableViewControllers with UISegementedControl - xamarin.ios

I've an UINavigationViewController with an UISegmentedControl in the navigation bar. I want to achieve a simple switching to different ViewControllers when users push on the segmented control.
I've tried a lot and nothing works... Considered sources:
MonoTouch Instantiating a ViewController programmatically for ContainerView
https://stackoverflow.com/search?q=viewcontroller+intptr+handle
And a lot of google research...
The whole project is storyboard based! Any solutions which targets NIB's aren't useful.
Adding a ContainerControl to my UINavigationViewController. But in this case I can only embed one controller. Creating a Embedded-Segue programmatically was not possible. Even more instantiating a UITableViewController in code which is designed in IB results in an empty view. Because I've to change the c'tor from MyTableViewController(IntPtr handle) : base(handle) to an empty constructor.
Can someone publish a working example how to use a UISegmentedControl to switch between different ViewControllers? I appreciate all your help very much.

Working solution:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CreateAndEmbed (TrDetailNavType.Info);
}
partial void segmentNavigationValueChanged (MonoTouch.UIKit.UISegmentedControl sender, MonoTouch.UIKit.UIEvent e)
{
CreateAndEmbed((TrDetailNavType)sender.SelectedSegment);
}
private void CreateAndEmbed(TrDetailNavType tab)
{
if (_currentViewController != null)
{
_currentViewController.View.RemoveFromSuperview ();
_currentViewController.RemoveFromParentViewController();
}
string id;
switch (tab)
{
case TrDetailNavType.Info:
id = "TagesRapportDetailInfoTableViewController";
break;
case TrDetailNavType.Lohn:
case TrDetailNavType.Material:
case TrDetailNavType.Inventar:
case TrDetailNavType.Fremdleistung:
case TrDetailNavType.Regie:
id = "TagesRapportDetailDummyViewController";
break;
}
_currentViewController = (UIViewController)Storyboard.InstantiateViewController (id);
_currentViewController.View.Frame = containerDetail.Bounds;
AddChildViewController (_currentViewController);
_currentViewController.DidMoveToParentViewController (this);
containerDetail.AddSubview (_currentViewController.View);
}

Related

MvvmCross and UIButton.Selected UISegmentedControl Bindings, iOS

In a cross platform Xamarin app built with the MvvmCross framework I'm using a ToggleButton Widget in an Android .axml layout. I've bound the Checked property to a View Model property using a converter using the following binding syntax:
Checked MarketBuySellViewModel.Direction, Converter=DirectionBool, ConverterParameter='Sell'
Everything works well. On the iOS side, it appears you can use UIButton as a ToggleButton by using the Selected property. This implies that the following binding should achieve what I want on iOS:
set.Bind (SellButton).For(b => b.Selected).To (vm => vm.MarketBuySellViewModel.Direction).WithConversion("DirectionBool", "Sell");
I don't get any binding errors in the application output but the binding itself doesn't seem to work. Clicking the button doesn't set the Direction property and setting the direction to a different value does not set the Selected property on the UIButton.
Do I need to create a Custom Binding or am I simply setting up the binding incorrectly?
I also tried using a UISegmentedControl to achieve the same effect. Is binding to this control supported at all in MvvmCross? I don't see any reference to it in the source code. Does this mean I need to create custom bindings for it too?
For the UIButton, I don't believe there's any included Selected binding built into MvvmCross. Because of this - and because Selected doesn't have a simple paired event SelectedChanged, then I believe Selected binding should work one-way (from ViewModel to View) but not two-way.
There is a binding for the On of a UISwitch control and that's the control I've seen used most in these situations.
If you wanted to add a custom 2-way binding for Selected then I guess you'd have to do this using the ValueChanged event (but would need to check that is correct).
To do so, you'd just build a target binding something like:
public class MvxUIButtonSelectedTargetBinding : MvxPropertyInfoTargetBinding<UIButton>
{
public MvxUIButtonSelectedTargetBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
var view = View;
view.ValueChanged += HandleValueChanged;
}
private void HandleValueChanged(object sender, System.EventArgs e)
{
var view = View;
if (view == null)
return;
FireValueChanged(view.Selected);
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.TwoWay; }
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
var view = View;
if (view != null)
{
view.ValueChanged -= HandleValueChanged;
}
}
}
}
and this could be registered in Setup in protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry) using something like:
registry.RegisterPropertyInfoBindingFactory(typeof(MvxUIButtonSelectedTargetBinding), typeof(UIButton),
"Selected");
Similarly, I don't believe anyone has added a two way UISegmentedControl binding yet - but would happily see one added.
Building a two way UISegmentedControl binding would be quite straight-forward - you'd just have to bind to the pair SelectedSegment and ValueChanged - with code similar to above.
Alternatively, you could switch to using a custom MySegmentedControl which had a nicer Value`ValueChanged` pair which would automatically work without a custom binding - e.g.:
public class MySegmentedControl : UISegmentedControl
{
// add more constructors if required
public int Value
{
get { return base.SelectedSegment; }
set { base.SelectedSegment = value; }
}
}
If any or all of these custom bindings are needed, then the Mvx project is happy to get these bindings added as issues or pull requests along with test/demo UIs in the https://github.com/slodge/MvvmCross-Tutorials/blob/master/ApiExamples/ApiExamples.Touch/Views/FirstView.cs project
Could be helpful to someone else, so i'm sharing my experience. I needed a two way binding for UISegmentedControl.SelectedSegment property to a ViewModel. The one way biding (ViewModel => View) works by default. I couldn't able to properly utilize the solution proposed by Stuart - to subclass the UISegmentedControl. I tried to ensure that the linker does not rip off the new custom control code, but this didn't help me a bit. So a perfectly viable solution is the one with MvxPropertyInfoTargetBinding. Here is the code working ok for me:
public class MvxUISegmentedControlSelectedSegmentTargetBinding : MvxPropertyInfoTargetBinding<UISegmentedControl>
{
public MvxUISegmentedControlSelectedSegmentTargetBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
this.View.ValueChanged += HandleValueChanged;
}
private void HandleValueChanged(object sender, System.EventArgs e)
{
var view = this.View;
if (view == null)
{
return;
}
FireValueChanged(view.SelectedSegment);
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.TwoWay; }
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (isDisposing)
{
var view = this.View;
if (view != null)
{
view.ValueChanged -= HandleValueChanged;
}
}
}
}
public class Setup : MvxTouchSetup
{
...
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterPropertyInfoBindingFactory(typeof(MvxUISegmentedControlSelectedSegmentTargetBinding), typeof(UISegmentedControl), "SelectedSegment");
}
}

Supporting two storyboards

I have an app with a medium-sized storyboard, which is complicated enough for me not to want to mess around with it too much.
I want to copy this storyboard and change the color scheme and let the user select which color scheme to use.
My question is: can I programmatically select which storyboard will be used by default on startup? If yes - how do I do that?
I looked at a somewhat related question: Storyboards Orientation Support in Xcode 4.5 and iOS 6.x ?
Based on that code I made an extension method:
static bool IsStoryboardLoading {get;set;}
public static T ConsiderSwitchingStoryboard<T> (this UIViewController from) where T: UIViewController
{
if (!IsStoryboardLoading && LocalStorage.Instance.IsWhiteScheme && false) {
try {
IsStoryboardLoading = true;
UIStoryboard storyboard = UIStoryboard.FromName ("MainStoryboard_WHITE", NSBundle.MainBundle);
T whiteView = storyboard.InstantiateViewController (typeof(T).Name) as T;
from.PresentViewController (whiteView, false, null);
return whiteView;
} finally {
IsStoryboardLoading = false;
}
}
return null;
}
}
and then I use it in ViewDidAppear override:
public override void ViewDidAppear (bool animated)
{
this.ConsiderSwitchingStoryboard<MyViewController> ();
}
This code works in some cases but in others it causes an error when performing a push segue:
NSGenericException Reason: Could not find a navigation controller for segue 'segSearchResults'. Push segues can only be used when the source controller is managed by an instance of UINavigationController.
at (wrapper managed-to-native) MonoTouch.ObjCRuntime.Messaging:void_objc_msgSendSuper_IntPtr_IntPtr (intptr,intptr,intptr,intptr)
It might be simpler to just use 1 Storyboard and have 2 sets of controllers in the same storyboard. Just use different storyboard ids for the controllers. You can use the same class on those if needed.
For example:
var whiteController = Storyboard.InstantiateViewController("MyWhiteController") as MyController;
var blueController = Storyboard.InstantiateViewController("MyBlueController") as MyController;
Both could create an instance of MyController, but pull out different layouts from the same storyboard file.
Another option is to use UIAppearance to dynamically set a "style" on all controls of a certain type in your app.
For example, to set the default UIBarButtonItem image throughout your app:
UIBarButtonItem.Appearance.SetBackgroundImage(UIImage.FromFile("yourpng.png"), UIControlState.Normal, UIBarMetrics.Detault);
(You might check my parameters there)

How do I prevent a single UIViewContoller from rotating in Monotouch? (All other views can rotate)

I have an iPhone app that supports all orientations but in one UIViewController I only want to support portrait (or upside down).
I have added the following code to my UIViewController but it still rotates.
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
return ((toInterfaceOrientation != UIInterfaceOrientation.LandscapeLeft) && (toInterfaceOrientation != UIInterfaceOrientation.LandscapeRight));
}
No matter where I add the ShouldAutorotateToInterfaceOrientation code it still rotates!
Is there a way to allow the app to support all orientations for all UIViewControllers except one?
Also i am using a NavigationController - does that affect things?
if you use iOS 6 you must override GetSupportedInterfaceOrientations method instead ShouldAutorotateToInterfaceOrientation
public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{ ... }
Probably this happens because your root navigation controller brings it own rotation. Lets assume that your root navigation controller is a normal UINavigationViewController. Create a derived own version:
public class UINavigationControllerWithoutRotation : UINavigationController
{
public UINavigationControllerWithoutRotation()
{
}
public UINavigationControllerWithoutRotation(UIViewController viewController) : base(viewController)
{
}
public override bool ShouldAutorotate()
{
return false;
}
}
Now use this as the root controller. Find the code saying something like:
var myRootController = new UINavigationController();
and replace it with
var myRootController = new UINavigationControllerWithoutRotation();
That should do the job. Keep in mind, that you have to do it a little bit different if for instance your root view controller is a UITabBarController!

Why would MonoTouch not garbage collect my custom UIButton unless I call button.RemoveFromSuperview()?

There seems to be something holding a reference to my custom button, MyButton (which inherits from UIButton), causing it not to be garbage collected unless I remove it from the superview. This, in turn, would cause the view controller that it is on to also not be finalized and collected.
In my example, I have my custom button but I also have a standard UIButton on the view controller which does not need to be removed from the superview in order to be collected. What's the difference? Looks pretty similar to me.
See this code. The irrelevant lines were removed for example's sake. Some things to note about the sample:
-MyButton is pretty empty. Just a constructor and nothing else overridden.
-Imagine MyViewController being on a UINavigationController
-LoadView() just creates the buttons, hooks up an event for each and adds it to the view
-Touching _button would push another MyViewController to the nav controller
-I'm doing some reference cleanup when popping view controllers off the nav controller in ViewDidAppear()
-In CleanUpRefs() you'll see that I have to remove _myButton from superview in order for all the objects to be garbage collected. _button, on the other hand does not need to be removed.
-I'm expecting the entire MyViewController to be collected, including all subviews, when popping from the nav controller but commenting out _myButton.RemoveFromSuperview() stops this from happening.
public class MyViewController : UIViewController
{
private UIButton _button;
private MyButton _myButton;
private MyViewController _nextController;
public override void LoadView()
{
base.LoadView();
_button = UIButton.FromType(UIButtonType.RoundedRect);
_button.TouchUpInside += PushNewController;
View.AddSubview(_button);
_myButton = new MyButton();
_myButton.TouchUpInside += MyButtonTouched;
View.AddSubview(_myButton);
}
private void PushNewController(object sender, EventArgs e)
{
_nextController = new MyViewController();
NavigationController.PushViewController(_nextController, true);
}
private void MyButtonTouched(object sender, EventArgs e)
{
Console.WriteLine("MyButton touched");
}
public void CleanUpRefs()
{
//_button.RemoveFromSuperview();
_myButton.RemoveFromSuperview();
// remove reference from hooking up event handler
_button.TouchUpInside -= PushNewController;
_myButton.TouchUpInside -= MyButtonTouched;
_button = null;
_myButton = null;
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if(_nextController != null)
{
_nextController.CleanUpRefs();
_nextController = null;
}
}
}
It seems as if there's something different with the fact that MyButton isn't a straight UIButton in that it is inherited. But then again, why would there be an extra reference count to it that's being removed by calling RemoveFromSuperview() especially when there's a UIButton just like it that doesn't need to be removed?
(I apologize for the really bad layout, stackoverflow seems to have problems laying out bullets right above code snippets)
Update: I filed a bug report with the MonoTouch team. You can download the sample project from there if you want to run it. Bug 92.
The reason for not garbage collecting in that scenario is just a bug in MonoTouch.
The upcoming MonoTouch release will contain a fix for this. If you are in a hurry, you can replace your /Developer/MonoTouch/usr/lib/mono/2.1/monotouch.dll with the copy I placed here:
http://tirania.org/tmp/monotouch.dll
I would make a backup, in case I did something wrong in my work-in-progress library.

How to use QLPreviewController in a non-modal way? Why does my code not work?

I have QLPreviewController up and running but I'm using PresentModalViewController() to show the QLPreviewController directly. For reasons beyond explanation, I would like to have my own UIViewController which will create its own view and within that view I would like to use the QLPreviewController. Should be easy I thought, but the code below just does nothing. The QLPreviewControllers ViewDidAppear never gets called. (In my example below, PreviewController inherits from QLPreviewController and encapsulates delegate, preview item and source).
Can somebody explain what is wrong with the code below (besides the fact that it is pointless :-))?
Oh, yeah: in my test scenario, I present the controller below modally. It shows up but witout the preview.
public class OuterPreviewController : UIViewController
{
public OuterPreviewController (QLPreviewControllerDataSource oDataSource) : base()
{
this.oDataSource = oDataSource;
}
private PreviewController oPreviewController;
private QLPreviewControllerDataSource oDataSource;
public override void LoadView ()
{
this.View = new UIView();
this.View.Frame = new RectangleF(0, 0, 500, 500);
this.View.BackgroundColor = UIColor.Red;
}
public override void ViewDidAppear (bool animated)
{
// Code execution comes her. No errors, no issues.
base.ViewDidAppear (animated);
this.oPreviewController = new PreviewController();
this.oPreviewController.DataSource = this.oDataSource;
// Preview controller's view is added but it never shows up.
this.View.AddSubview(this.oPreviewController.View);
this.oPreviewController.View.Frame = this.View.Frame;
this.oPreviewController.View.Center = this.View.Center;
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
return true;
}
}
Found a solution by coincidence today: all ReloadData() on the preview controller and magically it will show its contents.
This allows to add a QLPreviewController to an existing view as a subview and embed a preview. It also gets you rid of the toolbar which contains the open in menu.

Resources