在自定义UIView类中创建的Xamarin iOS子视图未显示
我有一个自定义UIView类,我想在其中添加一组子视图。这应该是一个简单的任务,但我似乎不明白为什么我的视图没有显示在UI上 这里的示例和教程非常简单,我相信我已经正确地实现了我的代码。我在在自定义UIView类中创建的Xamarin iOS子视图未显示,uiview,xamarin.ios,Uiview,Xamarin.ios,我有一个自定义UIView类,我想在其中添加一组子视图。这应该是一个简单的任务,但我似乎不明白为什么我的视图没有显示在UI上 这里的示例和教程非常简单,我相信我已经正确地实现了我的代码。我在AddSubview添加了一个断点,容器有一个大小 UIViewController类已经通过情节提要添加了背景图像 有人能帮我看看我可能遗漏了什么吗?我知道这是件小事 下面是我的代码: 自定义视图类 public class RotaryWheel : UIView { int numberOfSe
AddSubview
添加了一个断点,容器有一个大小
UIViewController类已经通过情节提要添加了背景图像
有人能帮我看看我可能遗漏了什么吗?我知道这是件小事
下面是我的代码:
自定义视图类
public class RotaryWheel : UIView
{
int numberOfSections;
public RotaryWheel(CGRect frame,int sections): base(frame)
{
numberOfSections = sections;
DrawWheel();
}
public void DrawWheel()
{
// derive the center x and y
float centerX = (float)(Frame.Width / 2);
float centerY = (float)(Frame.Height / 2);
container = new UIView();
container.Frame = new RectangleF(centerX, centerY, 100, 100);
container.BackgroundColor = UIColor.White;
AddSubview(container);
}
}
初始化视图的UIViewController类
public partial class HomePageController : UIViewController
{
public override void LoadView()
{
base.LoadView();
rotaryWheel = new RotaryWheel(new CGRect(20f, (float)(View.Frame.Height / 2), (float)View.Frame.Size.Width, (float)View.Frame.Height / 2f), 7);
View.AddSubview(rotaryWheel);
}
}
首先,请参阅。如文件所述
如果要对视图执行任何其他初始化,请在viewDidLoad()方法中执行
我们不应该在LoadView
中初始化子视图,所以我尝试将该代码移动到viewDidLoad
public override void ViewDidLoad()
{
base.ViewDidLoad();
RotaryWheel rotaryWheel = new RotaryWheel(new CGRect(20f, (float)(View.Frame.Height / 2), (float)View.Frame.Size.Width, (float)View.Frame.Height / 2f), 7);
View.AddSubview(rotaryWheel);
}
但看起来是这样的,子视图没有按预期定位
将该代码移动到viewdide
后,问题消失
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if(rotaryWheel == null){
rotaryWheel = new RotaryWheel(new CGRect(20f, (float)(View.Frame.Height / 2), (float)View.Frame.Size.Width, (float)View.Frame.Height / 2f), 7);
View.AddSubview(rotaryWheel);
}
}
总结:
View
的实际大小在方法viewdide
中显示。如果不使用autoLayout,则应小心管理视图框架
关于为什么你没有看到子视图,我猜你选择了iphone4、iPhone5或iPhone5S模拟器进行测试,屏幕宽度是320,你创建的RotaryWheel的X=20,centerX在方法
LoadView
中是300,所以它显示在屏幕外。Hi@Cole。你的回答肯定为我指明了正确的方向。谢谢我接受了。