带圆角的UIView有黑色背景

时间:2018-06-05 05:48:04

标签: ios swift uiview

我正在尝试创建一个圆角的UIView,圆角完美呈现,但视图后面有一个奇怪的黑色背景。如何摆脱黑色背景?

CODE

import UIKit
import PlaygroundSupport

// The background rectange for main view
let backgroundRectangle = CGRect(x: 0, y: 0, width: 500, height: 500)
// Main view
let mainView = UIView(frame: backgroundRectangle)
// Color of the main view
mainView.backgroundColor = .darkGray
// Corner radius
mainView.layer.cornerRadius = 50
mainView.layer.masksToBounds = false
// Present the view to Playground's live view
PlaygroundPage.current.liveView = mainView

RENDERED UI

UIVIEW

修改

import UIKit
import PlaygroundSupport

// Holder rectangle
let holderRectangle = CGRect(x: 0, y: 0, width: 500, height: 500)
// Holder view
let holderView = UIView(frame: holderRectangle)
// The background color of the holder view is clear
holderView.backgroundColor = .clear

// Main rectangle
let mainRectangle = CGRect(x: 0, y: 0, width: 500, height: 500)
// Main view
let mainView = UIView(frame: mainRectangle)
// The background color of the main view is black
mainView.backgroundColor = .white
// Create a corner radius for the main view
mainView.layer.cornerRadius = 30
mainView.layer.masksToBounds = false

// Make the main view a subview of the holder view
holderView.addSubview(mainView)

// Present the holder view in the live view
PlaygroundPage.current.liveView = holderView

1 个答案:

答案 0 :(得分:3)

这种情况正在发生,因为mainView后面没有其他视图。请在mainView后面添加一个视图,或将mainView嵌入UIView,将您选择的背景颜色分配给新创建的视图。多数民众赞成你解决了这个问题。