第一次绘制后 UIView 方向不正确

发布于 2024-09-25 07:59:00 字数 525 浏览 0 评论 0原文

我有一个视图控制器,每次触摸时都会交替显示两个视图。每个视图都会重写drawRect 函数。

当 iPad 处于纵向位置时,它可以工作,但对于横向位置,视图仅以正确的方向显示一次。此后,它们始终以纵向显示。

怎么了?

在视图控制器中:

- (void)loadView 
{
 v= [[View2 alloc] init];
 self.view =v;
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 x++;
 if (x%2==0)
 {
  v= [[View2 alloc] init];
 }
 else {
  v=[[View3 alloc] init];
 }
 self.view = v;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

I have a view controller that alternates 2 views on every touch. Each of the views overrides the drawRect function.

It works when the iPad is in portrait position but for landscape position, the view is shown in the right orientation only once. After that they always appear in portrait orientation.

What's wrong?

In ViewController:

- (void)loadView 
{
 v= [[View2 alloc] init];
 self.view =v;
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 x++;
 if (x%2==0)
 {
  v= [[View2 alloc] init];
 }
 else {
  v=[[View3 alloc] init];
 }
 self.view = v;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乖乖 2024-10-02 07:59:00

我解决了这个问题。这很简单而且有道理。基本上问题是只有第一个视图接收方向事件。更改视图时,必须再次连接事件处理程序,以便新视图可以检测方向。

一个简单的解决方法是创建一个虚拟视图作为父视图,并将 view1 和 view2 添加为子视图。我的新控制器代码如下:

- (void)loadView 
{
    self.view =[[UIView alloc] init];

    v= [[View2 alloc] init];
    [self.view addSubview:v];
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    x++;
    if (v!=NULL)
        [v removeFromSuperview];

    if (x%2==0)
    {
        v= [[View2 alloc] init];

    }
    else {
        v=[[View3 alloc] init];
    }

    [self.view addSubview:v];

}

I fixed the problem. It's simple and makes sense. Basically the problem is that only the FIRST view receives orientation events. When changing the view, event handlers must be hooked up again so that the new view can detect the orientation.

An easy fix is to create a dummy view as the parent and add view1 and view2 as subviews. My new controller code is as follow:

- (void)loadView 
{
    self.view =[[UIView alloc] init];

    v= [[View2 alloc] init];
    [self.view addSubview:v];
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    x++;
    if (v!=NULL)
        [v removeFromSuperview];

    if (x%2==0)
    {
        v= [[View2 alloc] init];

    }
    else {
        v=[[View3 alloc] init];
    }

    [self.view addSubview:v];

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文