如何在 iCarousel 视图框架中为每个图像添加标签

How to add a Label for Each Image in the iCarousel View Framework

我在我的视图控制器中使用了 iCarousel 框架。但是,我不确定如何在旋转木马视图中滚动时在每个图像下方添加标签。感谢您的帮助!谢谢!

 func numberOfItems(in carousel: iCarousel) -> Int {

return 10

}

func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {

let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width/1.4, height: 300))
view.backgroundColor = .red

let imageview = UIImageView(frame: view.bounds)
view.addSubview(imageview)
imageview.contentMode = .scaleToFill
imageview.image = UIImage(named: "Dog_\(index+1)")

return view

}

func carouselDidEndScrollingAnimation() {
  
if (myCarousel.currentItemIndex == 1) {
    
    dogNameLabel.text = "Brownie!"
    
}

}

let myCarousel: iCarousel = {
let view = iCarousel()
view.type = .rotary
return view
}()

override func viewDidLoad() {
super.viewDidLoad()

view.addSubview(myCarousel)
myCarousel.dataSource = self
myCarousel.frame = CGRect(x: 0, y: 220, width: view.frame.size.width, height: 400)
}

选项太多。您可以创建自定义视图 (xib) 以实现可重用性。需要在imageView上方的contentView中标注。

但是你需要像那样创建视图。

  func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width/1.4, height: 300))
        view.backgroundColor = .red
        
        let imageview = UIImageView(frame: view.bounds)
        view.addSubview(imageview)
        imageview.contentMode = .scaleToFill
        imageview.image = UIImage(named: "Dog_\(index+1)")
    
        let label = UILabel()
        label.text = "Enter your text"
        label.frame = CGRect(x: 0, y: 20, width: view.frame.size.width, height: 30)
        //or use constraints
    
        view.addSubview(label)
        
        return view
        
   }