UIbutton在旋转时以编程方式添加



我正在向视图添加UIButton,当我旋转设备时,屏幕上又添加了一个按钮。我只需要一个按钮,我不希望第二个按钮被添加到旋转。我试着为那个按钮设置自动调整大小的蒙版,但它没有像预期的那样工作。我使用了以下代码:

button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor lightGrayColor];
button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin;
[button setFrame:bFrame];   
[self addSubview:button];

我假设您提供的代码在方向改变时执行。

你要做的是将按钮存储在一个实例变量中,并在改变方向时检查该变量是否为nil。

if (!button) {
    button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.backgroundColor = [UIColor lightGrayColor];
    button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin |
    UIViewAutoresizingFlexibleRightMargin |
    UIViewAutoresizingFlexibleTopMargin |
    UIViewAutoresizingFlexibleBottomMargin;
    [button setFrame:bFrame];   
    [self addSubview:button];
}

这里假设变量buttonUIViewUIViewController的实例变量,而不是仅在方法范围内的变量。

关于您的autoresizingMask,请说明您期望发生的情况和实际发生的情况,以便我们帮助您。

最新更新