MonoTouch Set Position from SubView

2019-02-27 03:18发布

问题:

Hey Guys i´m new to MonoTouch and have a problem. Can anyone of you tell me how to set the Position of a subview? I tried this:

UIImageView imageview = new UIImageView(this.ImageSource);

this.AddSubview(imageview);

this.Subviews[0].Bounds.X = 30;

I hope anyone of you can help me.

Thanks

回答1:

Beside Bounds or Frame (mentioned by @Krumelur) there's a .NET issue in your code.

RectangleF is a value-type (struct), not a reference type. You cannot change their properties / fields in .NET without creating a new instance (directly or indirectly);

i.e. the property getter for Bounds will always return a new instance. So you assignment of 30 is done on an instance different than the one Subviews[0] is using.

Proof:

Console.WriteLine (Object.ReferenceEquals (this.Subviews[0].Bounds,
    this.Subviews[0].Bounds)); // prints 'False'

So what you need to do in such case is:

var bounds = this.Subviews[0].Bounds;
bounds.X = 30.0f;
this.Subviews[0].Bounds = bounds;

So the new RectangleF (struct) instance is assigned back to the Bounds property (with the new value you set).



回答2:

The Bounds property gives you, well, the bounds of the view. If you want to reposition it, use:

var vourView = this.Subviews[0];
yourView.Frame = new RectangleF(new PointF(x, y), yourView.Bounds.Size);

or

yourView.Center = new PointF(newCenterX, newCenterY)