首页 文章

UIBarButtonItem具有单独的纵向和横向图像 - 从UINavigationController弹出视图控制器时未调用layoutSubviews

提问于
浏览
3

我想在UINavigationController的UIToolbar中显示完全自定义按钮, and support portrait and landscape . 目前我已经实现了一个RotatingButton(一个UIView子类)类,它包含一个填充整个RotatingButton框架的UIButton . RotatingButton还包含两个图像,用于纵向和横向,并且这些图像的高度不同 . 然后将此RotatingButton作为自定义视图包装到UIBarButtonItem中 .

目前,在RotatingButton的layoutSubviews中,我设置了整个视图的边界,并为当前方向设置了适当的图像 . 这很好用,可以根据需要处理旋转 .

- (void) createLayout {
    [self addButtonIfNeeded];
    UIDeviceOrientation currentOrientation = [[UIDevice currentDevice] orientation];
    if(UIInterfaceOrientationIsLandscape(currentOrientation)) {
        [self.button setImage:self.landscapeImage forState:UIControlStateNormal];
        self.button.frame = CGRectMake(0.0, 0.0, self.landscapeImage.size.width / 2, self.landscapeImage.size.height / 2);
        self.bounds = CGRectMake(0.0, 0.0, self.landscapeImage.size.width / 2, self.landscapeImage.size.height / 2);
    } else {
        [self.button setImage:self.portraitImage forState:UIControlStateNormal];
        self.button.frame = CGRectMake(0.0, 0.0, self.portraitImage.size.width / 2, self.portraitImage.size.height / 2);
        self.bounds = CGRectMake(0.0, 0.0, self.portraitImage.size.width / 2, self.portraitImage.size.height / 2);
    }
}

- (void) layoutSubviews {
    [super layoutSubviews];
    [self createLayout];
}

但是,这个问题仍然存在:

  • 纵向开始视图

  • 将视图控制器推入堆栈

  • 将设备旋转为横向(当前视图反应正确)

  • 弹出最后一个视图控制器:上一个视图反应良好,但RotatingButtons ' layoutSubviews don'被调用, and the buttons remain larger than they should .

所以,目前在弹出一个视图控制器之后,之前的UIBarButtonItems没有调用它们的layoutSubviews,它们仍然太大(或者太小,如果我们从横向开始并在另一个视图中旋转到肖像) . 如何解决这个问题呢?

2 回答

  • 0

    这是一个非常棘手的问题 . 您应该尝试重写 viewWillAppear: 来调用 [self.view setNeedsLayout] 以在视图即将出现时强制进行布局更新 .

  • 1

    我没有找到一个完全令人满意的解决方案,但我的按钮恰好是合适的尺寸,这种解决方案对我来说效果非常好:

    UIBarButtonItem* b = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:target action:selector];
    UIImage *barButton = [portraitImage resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    UIImage *barButton_land = [landscapeImage resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [b setBackgroundImage:barButton forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [b setBackgroundImage:barButton_land forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone];
    

    然后显然将创建的按钮添加为rightBarButtonItem / leftBarButtonItem,或者您可能想要使用它 .

    这样做的问题是,如果按钮不够宽,按钮可能看起来完全错误(因为图像的中间内容在此解决方案中平铺) .

相关问题