iCarousel自定义视图xib自动更改子视图宽度

时间:2016-10-10 02:49:25

标签: ios swift xcode icarousel

我尝试使用XIB UI向iCarousel视图添加自定义视图,但在初始化并运行时,轮播视图子视图的宽度会自动更改。

func carousel(carousel: iCarousel!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! {

    var itemView: ProfileQuestionView

    //create new view if no view is available for recycling
    if (view == nil) {

        itemView    =   UINib.init(nibName: "ProfileQuestionView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! ProfileQuestionView
        itemView.frame              =  CGRect.init(x: 20, y: 10, width: self.view.frame.width-40, height: self.carouselView.frame.height-20)

        itemView.layer.borderColor  =  UIColor.clearColor().CGColor
        itemView.layer.borderWidth  =  0.5
        itemView.layer.cornerRadius =  5.0;
        itemView.layoutIfNeeded()

    } else {

        //get a reference to the label in the recycled view
        itemView = view as! ProfileQuestionView

        itemView.layoutIfNeeded()
    }

    return itemView
}

不知道为什么会出现这个问题。

carouselView.type = iCarouselType.Rotary

3 个答案:

答案 0 :(得分:0)

它只是一个打击并尝试。不确定它会起作用。

尝试更改此行

itemView.frame = CGRect.init(x: 20, y: 10, width: self.view.frame.width-40, height: self.carouselView.frame.height-20)

itemView.frame = CGRect.init(x: 20, y: 10, width: UIScreen.mainScreen().bounds.width-40, height: self.carouselView.frame.height-20)

好像您正在viewDidLoad重新加载轮播时,约束仍未设置。

还可以尝试按标记获取商品。

if (view == nil) {
     itemView = UINib.init(nibName: "ProfileQuestionView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! ProfileQuestionView

    // give a tag
    itemView.tag = 1
    //Then your rest of the code
    } else {
     // Reusability
     itemView = (view?.viewWithTag(1))!
}

希望能解决问题。

答案 1 :(得分:0)

我在Xcode 8上遇到了这个问题,但我的代码在Xcode 7.3.1上运行良好。 将初始化轮播放在viewDidLayoutSubviews

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //Check if carousel is initialized or not
        if self.carousel.dataSource == nil {
            //Init your carousel here
        }
    }

答案 2 :(得分:0)

在viewDidLayoutSubviews()

中初始化轮播的类型
  

方法 viewDidLayoutSubviews()

 override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // carousel type
    yourCarouselName.type = .custom
}