2013-04-29 80 views
15

您之前可能已經看到過它,它在ScoutMob等消費時尚應用中變得非常流行。我試圖在啓動時實現60%的透明視圖,這將覆蓋我的主屏幕,解釋如何使用主屏幕的功能並在點擊時消失。如何在當前視圖上創建半透明視圖圖層?

我有我的整個應用程序完成(這是使用的.xib的,因爲它從一年前,但隨時在故事板格式,以及解釋,因爲我可能會重用在其他iOS 5.0+應用此功能)。

我沒有問題製作單個視圖,但是暫時將一個視圖重疊在另一個視圖上是我沒有直觀地理解的。我會繼續研究,幷包含任何有用的提示,以供其他人試圖做同樣的事情。

+1

[相關問題](http://stackoverflow.com/questions/849458/transparent-modal-view-on-navigation-controller/859215#859215),雖然有點過時 – user 2013-04-29 16:12:52

回答

43
// get your window screen size 
CGRect screenRect = [[UIScreen mainScreen] bounds]; 
//create a new view with the same size 
UIView* coverView = [[UIView alloc] initWithFrame:screenRect]; 
// change the background color to black and the opacity to 0.6 
coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6]; 
// add this new view to your main view 
[self.view addSubview:coverView]; 

,當你用它做,你可以將其刪除:

[coverView removeFromSuperview]; 

Swift3版本:

// get your window screen size 
let screenRect = UIScreen.main.bounds 
//create a new view with the same size 
let coverView = UIView(frame: screenRect) 
// change the background color to black and the opacity to 0.6 
coverView.backgroundColor = UIColor.black.withAlphaComponent(0.6)   
// add this new view to your main view 
self.view.addSubview(coverView) 

將其刪除:

coverView.removeFromSuperview() 
1

就作出這樣的數字,如果它是國內首家推出應用程序的機制,然後告訴您的主視圖控制器對當前視圖頂部添加一個(可能是圖像)視點與0.6阿爾法

if (figureOutIfIsFirstLaunch) 
{ 
    UIImageView *myOverlay = [...]; 
    myOverlay.frame = self.view.bounds; 
    myOverlay.alpha = 0.6; 
    [self.view addSubview:myOverlay]; 
} 
+0

會有什麼反響這在我的applicationDelegate的'應用程序:didFinishLaunchingWithOptions:'而不是包含視圖的控​​制器? – user 2013-04-29 17:30:40

4

這可以很容易地用UITextView和UIButton完成。只需簡單地將UITextView的你要顯示的內容在屏幕上,使得它的屏幕的全框的大小,改變背景顏色爲黑色背景.6

[UIColor colorWithRed: 0 withGreen: 0 withBlue: 0 withAlpha: .6]; 

背景Alpha然後把按鈕作爲頂層的子視圖,使其成爲屏幕的全幀,並將其設置爲0.設置按鈕的操作以隱藏文本視圖和按鈕。

例子:

UITextView* textview = [[UITextView alloc] initWithFrame:self.view.frame]; 
[textview setText: @"Text here"]; 
[textview setBackgroundColor: [UIColor colorWithRed: 0 withGreen: 0 withBlue: 0 withAlpha: .6]]; 
[textview setTextColor: [UIColor whiteColor]]; 
[self.view addSubview: textview]; 

UIButton* btn = [[UIButton alloc] initWithFrame:self.view.frame]; 
[btn setAlpha:0]; 
[btn addTarget:self action:@selector(method) forEvent:UIControlEventTouchUpInside]; 
[self.view addSubview: btn]; 

你可能要檢查的addTarget:方法;我不確定這些是否是我頭頂的正確參數。

1
  1. 創建UIView,將其命名爲你想要的東西(dimBackgroundUIView)然後設置 的的backgroundColor爲黑色,並設置阿爾法0.1或0.2或....
  2. 當你需要調暗 背景添加這些兩行代碼:[self.view addSubview:dimBackgroundUIView]; [self addConstraintsForDimView];
  3. ,當你要刪除的調光 背景添加這些兩行代碼:if(dimBackgroundUIView) [dimBackgroundUIView removeFromSuperview];
  4. 不要忘了加約束(佈局)爲 dimBackgroundUIView

檢查:iOS Dim background when a view is shown

,不要忘了閱讀的代碼下面的注意事項,瞭解你必須做什麼。

+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/評論/低質量/職位/ 10848678) – 2016-01-11 11:06:18

+1

好的,我解決了我的答案 – 2016-01-11 12:02:35