【发布时间】:2021-09-19 08:39:57
【问题描述】:
从我的 CGColor 数组中的项目设置我的 UIView .backgroundColor 会导致构建错误:
“没有更多上下文,表达式的类型不明确”
(在代码底部)
我想显示 UIView 矩形并控制每个矩形的颜色。
这是代码——底部的构建错误..
class ViewController: UIViewController
{
// the array of UIView's, one for each rectangle:
static var map_sectors_UIView: [UIView] = []
override func viewDidLoad()
{
// init the UIView array:
for map_sector_index in 0...App.total_map_sectors-1
{
let new_UIView = UIView()
new_UIView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
ViewController.map_sectors_UIView[ map_sector_index ] = new_UIView
}
super.viewDidLoad()
// Add the subviews:
for map_sector_index in 0...App.total_map_sectors-1
{
view.addSubview( ViewController.map_sectors_UIView[ map_sector_index ] )
}
. . .
// init each UIView rectangle:
ViewController.map_sectors_UIView[ map_sector_index ].frame = CGRect( x: map_sector_column * App.sector_width_pix,
y: map_sector_row * App.sector_height_pix,
width: App.sector_width_pix,
height: App.sector_height_pix )
ViewController.map_sectors_UIView[ map_sector_index ].backgroundColor = .green
. . .
class App
{
static var sector_colors_array: [CGColor] = []
. . .
static func init_class()
{
// Declare array of colors for the UIView rectangles:
sector_colors_array = [CGColor]( repeating: UIColor.black.cgColor,
count: total_map_sectors )
}
. . .
// Display all the rectangles:
DispatchQueue.main.sync
{
ViewController.map_sectors_UIView[ sector_index ].backgroundColor = sector_colors_array[ sector_index ]
.......... gets build error: "Type of expression is ambiguous without more context"
【问题讨论】:
-
为什么都是
static? -
你为什么感到惊讶?你说过自己
sector_colors_array是一个CGColor 数组。但是视图的backgroundColor不是 CGColor。因此,有问题的行对编译器(或对人类)来说是有意义的。 -
加上@matt 所说的,
backgroundColor接受UIColor,而不是CGColor