#ios #swift #uiview #cgcolor
Вопрос:
Установка моего UIView .backgroundColor из элемента в моем массиве CGColor вызывает ошибку сборки:
«Тип выражения неоднозначен без дополнительного контекста»
(внизу кода)
Я хочу отображать прямоугольники 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"
Комментарии:
1. Почему все
static
так ?2. Почему ты удивляешься? Вы сами сказали
sector_colors_array
, что это массив CGColor. Но представление-этоbackgroundColor
не цвет CG. Таким образом, рассматриваемая строка имеет смысл для компилятора (или для человека).3. Добавление к тому, что сказал @matt ,
backgroundColor
включает в себяUIColor
, а неCGColor
Ответ №1:
Спасибо, Мэтт. Легко исправить. Просто заменил ссылки на CGColor на UIColor.