Прямо сейчас у меня есть collectionView, для которого каждая ячейка содержит горизонтальный stackView.StackView заполняется серией UIViews (прямоугольников), по одному на каждый день месяца - каждая ячейка соответствует месяцу.Я заполняю представления стека следующим образом:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionView {
...
return cell
} else if collectionView == self.timeline {
let index = indexPath.row
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: timelineMonthCellReuseIdentifier, for: indexPath) as! SNTimelineMonthViewCell
let firstPost = posts.first?.timeStamp
let month = Calendar.current.date(byAdding: .month, value: index, to: firstPost!)
print(dateFormatter.string(from: month!),dateFormatter.string(from: firstPost!),"month diff")
for post in posts {
print(post.timeStamp, "month diff")
}
cell.monthLabel.text = dateFormatter.string(from: month!)
cell.monthLabel.textAlignment = .center
if let start = month?.startOfMonth(), let end = month?.endOfMonth(), let stackView = cell.dayTicks {
var date = start
while date <= end {
let line = UIView()
if posts.contains(where: { Calendar.current.isDate(date, inSameDayAs: $0.timeStamp) }) {
line.backgroundColor = UIColor(red:0.15, green:0.67, blue:0.93, alpha:1.0)
let tapGuesture = UITapGestureRecognizer(target: self, action: #selector (self.tapBar (_:)))
line.isUserInteractionEnabled = true
line.addGestureRecognizer(tapGuesture)
self.dayTicks[date] = line
} else {
line.backgroundColor = UIColor.clear
}
stackView.addArrangedSubview(line)
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
}
}
return cell
} else {
preconditionFailure("Unknown collection view!")
}
}
Затем, когда пользователь прекращает прокручивать другое представление коллекции, я хочу добавить подпредставление arrowView поверх dayTick (посмотрите, как self.dayTicks заполняетсяподпредставления stackView выше).
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentIndex = self.collectionView.contentOffset.x / self.collectionView.frame.size.width
let post = posts[Int(currentIndex)]
for (_,tick) in self.dayTicks {
tick.subviews.forEach({ $0.removeFromSuperview() })
}
let day = Calendar.current.startOfDay(for: post.timeStamp)
let tick = self.dayTicks[day]
let arrow = UIImage(named:"Tracer Pin")
let arrowView = UIImageView(image: arrow)
// arrowView.clipsToBounds = false
print((tick?.frame.origin)!,"tick origin")
// arrowView.frame.origin = (tick?.frame.origin)!
// arrowView.frame.size.width = 100
// arrowView.frame.size.height = 100
tick?.addSubview(arrowView)
}
Этот вид работ выглядит так:
![enter image description here](https://i.stack.imgur.com/BaBEs.png)
Красный прямоугольник добавлен, но он отображается насправа от dayTick, и он выглядит как длинный тонкий прямоугольник.В действительности, изображение Tracer Pin, на которое ссылаются, выглядит так:
![enter image description here](https://i.stack.imgur.com/Jzofp.png)
По крайней мере, откуда берется красный цвет, но, как вы можете видеть, он растягиваетсястранно и обрезает все, что не в прямоугольном пространстве UIView.
Теперь обратите внимание, что я закомментировал 4 строки, которые устанавливают размер и происхождение arrowView, а также устанавливают для clipToBounds значение false.Когда я раскомментирую эти строки - arrowView просто не появляется вообще, поэтому я, должно быть, поступаю неправильноЯ хочу показать что-то вроде этого:
![enter image description here](https://i.stack.imgur.com/hZXtR.png)
Как я могу поставить это прямо сверху?