是否可以在UIAlertView上垂直布置2个按钮?

Vol*_*da2 5 uialertview ios

我想用两个按钮创建UIAlertView.我需要垂直布置这些按钮(我的文字太大了).可能吗 ?

屏蔽1

在此输入图像描述

画面2

在此输入图像描述

Flo*_*Flo 8

似乎没有SDK支持此行为.UIAlertView中的两个按钮将始终以水平布局显示.

但是,将UIAlertView子类化以获得预期的行为非常容易.我们来调用VerticalAlertView类.

以下代码仅适用于具有两个按钮的警报视图,因为UIAlertView中的两个以上按钮将自动以垂直布局显示.

VerticalAlertView.h就像这样简单:

#import <UIKit/UIKit.h>

@interface VerticalAlertView : UIAlertView
@end
Run Code Online (Sandbox Code Playgroud)

VerticalAlertView.m:

#import "VerticalAlertView.h"

@implementation VerticalAlertView

- (void)layoutSubviews
{
    [super layoutSubviews];

    int buttonCount = 0;
    UIButton *button1;
    UIButton *button2;

    // first, iterate over all subviews to find the two buttons;
    // those buttons are actually UIAlertButtons, but this is a subclass of UIButton
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            ++buttonCount;
            if (buttonCount == 1) {
                button1 = (UIButton *)view;
            } else if (buttonCount == 2) {
                button2 = (UIButton *)view;
            }
        }
    }

    // make sure that button1 is as wide as both buttons initially are together
    button1.frame = CGRectMake(button1.frame.origin.x, button1.frame.origin.y, CGRectGetMaxX(button2.frame) - button1.frame.origin.x, button1.frame.size.height);

    // make sure that button2 is moved to the next line,
    // as wide as button1, and set to the same x-position as button1
    button2.frame = CGRectMake(button1.frame.origin.x, CGRectGetMaxY(button1.frame) + 10, button1.frame.size.width, button2.frame.size.height);

    // now increase the height of the (alert) view to make it look nice
    // (I know that magic numbers are not nice...)
    self.bounds = CGRectMake(0, 0, self.bounds.size.width, CGRectGetMaxY(button2.frame) + 15);
}

@end
Run Code Online (Sandbox Code Playgroud)

您现在可以像使用任何其他UIAlertView一样使用您的类:

[[[VerticalAlertView alloc] initWithTitle:@"Title" 
                                  message:@"This is an alert message!" 
                                 delegate:self 
                        cancelButtonTitle:@"OK" 
                        otherButtonTitles:@"Second Button", nil] autorelease] show];
Run Code Online (Sandbox Code Playgroud)

您将得到以下结果:

在此输入图像描述

编辑:

使用这种方法有点风险(更不用说hacky),因为Apple可能会在某些时候改变UIAlertView的实现,这可能会破坏你的布局.我只想指出,这对您的问题来说是一个简单快捷的解决方案.如UIAlertView参考中所述:

"UIAlertView类旨在按原样使用,不支持子类化.此类的视图层次结构是私有的,不得修改."


Ian*_*n L 4

默认情况下这是不可能的。nycynik 的答案中显示的外观是当您有两个以上按钮时会发生的情况。

因此,要么添加另一个按钮,要么您可以查看第三方解决方案,例如此库,尽管我还没有测试过它。