Swift:覆盖矩形,文本在视图上方

时间:2017-03-30 02:11:54

标签: ios swift shape

如果我们的应用有网络连接错误,我们希望在屏幕顶部覆盖一个彩色透明矩形,其中一些"网络不可用"喜欢文字。矩形应覆盖屏幕的整个宽度,高度应足以显示文本。我们将使用计时器仅在短时间内显示矩形。你怎么能这样做?

实际视图可能是UITableViewController,UIViewController或其他东西......

2 个答案:

答案 0 :(得分: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()
}

答案 1 :(得分:0)

我做覆盖的方法是将新的UIViewController拖到故事板中,然后将UIView拖到其中。在布置UI时,使UIViewController黑色的背景颜色变得有用。当您在UIView内完成元素的布局后,请将UIViewController的背景颜色更改为透明。

以下是个人资料叠加的示例:

screenshot of an overlay view controller in a storyboard

在这种情况下,我实际上将UIViewController背景设为灰色,其alpha值约为50%。然后,当我使用淡入淡出过渡呈现此视图控制器时,它看起来好像显示在当前上下文之上:

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内创建的视图的背景颜色故事板。