如果你想在代碼中完成它,下面是一個例子,我只是使用惰性加載的UI元素來鼓掌。我只在這裏製作一個按鈕,並在任何一個視圖處於活動狀態之間進行交換。這有點尷尬,但它減少了證明這一點所需的代碼量。
我已經創建了兩個UIViews來表示您的自定義類,其中一個具有藍色背景,另一個具有紅色。按鈕在兩者之間交換。如果每個自定義視圖中都有一個唯一的按鈕,則只需將這些按鈕公開爲UIView子類的屬性,以便您的視圖控制器可以訪問它們,或將視圖控制器添加爲內部按鈕操作的目標你的UIView的加載代碼。
我已經在我的模擬器中測試了這段代碼,它似乎工作正常,但是您應該嘗試瞭解這裏發生了什麼,以便您可以自己實現它。
ToggleViewController.h:
#import <UIKit/UIKit.h>
@interface ToggleViewController : UIViewController {
UIView *firstView;
UIView *secondView;
UIButton *button;
}
- (void)addButton;
- (void)toggleViews;
@property (nonatomic, readonly) UIView* firstView;
@property (nonatomic, readonly) UIView* secondView;
@property (nonatomic, readonly) UIButton* button;
@end
ToggleViewController.m:
#import "ToggleViewController.h"
@implementation ToggleViewController
// assign view to view controller
- (void)loadView {
self.view = self.firstView;
}
// make sure button is added when view is shown
- (void)viewWillAppear:(BOOL)animated {
[self addButton];
}
// add the button to the center of the view
- (void)addButton {
[self.view addSubview:self.button];
button.frame = CGRectMake(0,0,150,44);
button.center = self.view.center;
}
// to toggle views, remove button from old view, swap views, then add button again
- (void)toggleViews {
[self.button removeFromSuperview];
self.view = (self.view == self.firstView) ? self.secondView : self.firstView;
[self addButton];
}
// generate first view on access
- (UIView *)firstView {
if (firstView == nil) {
firstView = [[UIView alloc] initWithFrame:CGRectZero];
firstView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
firstView.backgroundColor = [UIColor redColor];
}
return firstView;
}
// generate second view on access
- (UIView *)secondView {
if (secondView == nil) {
secondView = [[UIView alloc] initWithFrame:CGRectZero];
secondView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
secondView.backgroundColor = [UIColor blueColor];
}
return secondView;
}
// generate button on access
- (UIButton *)button {
if (button == nil) {
// create button
button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
// set title
[button setTitle:@"Toggle Views"
forState:UIControlStateNormal];
// set self as a target for the "touch up inside" event of the button
[button addTarget:self
action:@selector(toggleViews)
forControlEvents:UIControlEventTouchUpInside];
}
return button;
}
// clean up
- (void)dealloc {
[button release];
[secondView release];
[firstView release];
[super dealloc];
}
@end
@Victorb感謝這是偉大的東西。順便說一句,我不得不使用initWithFrame:[[UIScreen mainScreen] applicationFrame]我的firstView方法而不是CGRectZero讓它在模擬器中工作任何想法爲什麼? – PeanutPower
在我的測試中,我將VC添加到標籤欄控制器,以便框架已經建立。我的猜測是,無論你使用什麼容器都沒有正確的框架集。自設置autoresizingMask後,CGRectZero框架應在超級視圖中進行更改。但是如果你的框架能夠按照你的方式工作,那就去吧。 – VictorB