首页 > 解决方案 > 带圆角的 UIView 具有黑色背景

问题描述

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

代码

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

渲染的用户界面

界面视图

编辑

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

标签: iosswiftuiview

解决方案


发生这种情况是因为,您的mainView. 请在后面添加一个视图mainView或将您的视图嵌入mainViewUIView为新创建的视图分配您选择的背景颜色。那就是你的问题解决了。


推荐阅读