簡體   English   中英

以編程方式創建UISwitch

[英]Creating a UISwitch Programmatically

在一個看似永無止境的關於iphone開發的更多努力中,我一直在玩蘋果開發者網站提供的一些源代碼。 我正在使用的特定示例是Core Data Books,可在此處找到。 DetailViewController和AddViewController是以編程方式創建的,因為它們沒有任何xib文件。 我的問題是在不使用IB的情況下以編程方式將視圖添加到視圖中。 我想在UITableView下面放置一個UISwitch,它包含DetailView中特定書籍的詳細信息。 我該怎么做呢? 這是我到目前為止所嘗試的:

在AddViewController中,我設置了UISwitch:

@interface AddViewController : DetailViewController {
id <AddViewControllerDelegate> delegate;
UISwitch *onoff;

 }

@property (nonatomic, assign) id <AddViewControllerDelegate> delegate;
@property (nonatomic, retain) IBOutlet UISwitch *onoff;

我還設置了一個IBAction:

- (IBAction)flip:(id)sender;

然后我在AddViewController.m文件中合成它,但沒有任何反應。 我只需要設置開關並使其成為可以控制它從我設置的IBAction中做的事情。 我知道這很簡單,但我無法弄清楚。 所以,任何幫助將不勝感激! 謝謝

編輯1

所以我實現了我在viewDidLoad中指向的代碼,如下所示:

   - (void)viewDidLoad {

[super viewDidLoad];    
  UISwitch *onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
[onoff addTarget: self action: @selector(flip:) forControlEvents:UIControlEventValueChanged];
// Set the desired frame location of onoff here
[self.view addSubview: onoff];

並且它拋出兩個警告,說'onoff'的本地聲明隱藏了實例變量。 但即使有這些收益,UISwitch彈出也好,但是當我移動或使用它時,它看起來並不完全正常。 對於我的行為,看起來像這樣:

- (IBAction)flip:(id)sender {
if (onoff.on) NSLog(@"On");  
else  NSLog(@"Off");  
 }

每當開關打開時,控制台應該打開,當它關閉時,控制台應該讀取。 對? 無論何時我移動它,它只是在控制台中重復,關閉。 如果它打開,或者它關閉,它只顯示。 世界上我做錯了什么? 請幫忙! 謝謝

編譯器正試圖幫助你。 您正在覆蓋viewDidLoad;的onoff實例變量viewDidLoad; 因此,這永遠不會被設定。 在你的-flip:方法中,你引用了一個nil控制器。 有兩種方法可以解決這個問題:

(a)擺脫onoff的本地聲明,只使用你的實例變量

(b)將sender參數轉換為-flip:作為UISwitch ,並訪問:

- (IBAction) flip: (id) sender {
    UISwitch *onoff = (UISwitch *) sender;
    NSLog(@"%@", onoff.on ? @"On" : @"Off");
}

史蒂夫,如果我誤解了你的問題,我很抱歉。 您是否實際創建了UISwitch並將其添加到視圖層次結構中? 您的控制器的-loadView-viewDidLoad實現應具有以下代碼:

// Use the ivar here
onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
[onoff addTarget: self action: @selector(flip:) forControlEvents: UIControlEventValueChanged];
// Set the desired frame location of onoff here
[self.view addSubview: onoff];
[onoff release];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM