2017-03-30 76 views
0

如果我们的应用程序存在网络连接错误,我们希望覆盖屏幕顶部的彩色透明矩形,并使用“网络不可用”(如文本)。矩形应该覆盖屏幕的整个宽度,高度应该足以显示文本。我们将使用计时器仅显示矩形一段时间。你怎么能这样做?Swift:文本覆盖的矩形视图

实际的看法可能是一个UITableViewController,一个UIViewController,还是其他什么东西......

回答

2

你可以这样做:

let deadlineTime = DispatchTime.now() + .seconds(2) 

let window = UIApplication.shared.keyWindow! 

let rectangleView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20)) 
rectangleView.backgroundColor = UIColor.red 

let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 20)) 
label.text = "Network not available" 

rectangleView.addSubview(label) 

window.addSubview(rectangleView) 

DispatchQueue.main.asyncAfter(deadline: deadlineTime) { 
    rectangleView.removeFromSuperview() 
} 
+0

谢谢,我会试试这个。 –

0

我已经做了叠加的方法是将一个新的UIViewController成故事板,并拖动一个UIView成。在布置用户界面时,将背景色改为黑色可能会有帮助。当您完成UIView内部的布局时,请将UIViewController的背景颜色更改为透明。

这里有一个轮廓覆盖的例子:

screenshot of an overlay view controller in a storyboard

在这种情况下,我实际上约50%的α-作出UIViewController背景灰色。然后,当我提出用淡出过渡看起来它似乎在顶部的当前背景下,这个视图控制器:

func showOverlay() { 
    // 
    guard let vc = UIStoryboard(name: "MyStoryboard", bundle: nil).instantiateViewController(withIdentifier: "myOverlay") as? UIViewController else { 
     print("failed to get myOverlay from MyStoryboard") 
     return 
    } 

    vc.modalPresentationStyle = .overCurrentContext 
    vc.modalTransitionStyle = .crossDissolve 

    self.present(vc, animated: true, completion: { 
     // after 3 seconds, dismiss the overlay 
     dispatchAfterSeconds(3) { 
      vc.dismiss(animated: true) 
     } 
    }) 
} 

它使用一个方便的功能,dispatchAfterSeconds

// execute function after delay using GCD 
func dispatchAfterSeconds(_ seconds: Double, completion: @escaping (() -> Void)) { 
    let triggerTime = Int64(Double(NSEC_PER_SEC) * seconds) 
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(triggerTime)/Double(NSEC_PER_SEC), execute: {() -> Void in 
     completion() 
    }) 
} 

需要注意的是,当我谈论改变UIViewController的背景颜色,我实际上所指的是在故事板中创建的默认情况下在UIViewController内创建的视图的背景颜色。

+0

感谢您的答复。但我之后的解决方案只会在屏幕顶部显示带有文本的栏(矩形)。显示文字时,实际的屏幕仍然可用。也就是说:文本会出现在桌子上,当文字出现时,您仍然可以滚动桌子。 Instagram为他们的联网提示信息使用了类似的方法。看起来,这种方法完全显示了新视图,使现有视图在显示警报时不可用。 –