看新浪微博的時(shí)候,新聞詳情頁(yè)下面那塊的廣告模塊,圖片是可以跟著ScrollView的滑動(dòng)而變化位置的,效果挺好玩,就模擬的做了一個(gè)。第一感覺是UIview新增屬性了,可以通過變化錨點(diǎn)而改變位置,后來發(fā)現(xiàn)我還是太年輕了,這只是UIView和UIimageView組合的效果而已。

具體實(shí)現(xiàn)思路是這樣:一個(gè)UIView作為父視圖,UIimageView添加到這個(gè)UIView上,UIimageView的frame要比UIView的大,把UIView添加到UIScrollView上,滾動(dòng)的時(shí)候改變UIimageView的起始點(diǎn)位置就可以了, 是不是很簡(jiǎn)單???
我自定義了一個(gè)YLMoveImageView,在init方法中代碼如下:
func setupView() {
? ? ? ? self.clipsToBounds = true
? ? ? ? self.contentMode = UIViewContentMode.scaleAspectFill
? ? ? ? self.addSubview(self.m_imageView)
? ? }
clipsToBounds屬性必須設(shè)置為true,為了盡量不失真,需要設(shè)置self.contentMode = UIViewContentMode.scaleAspectFill,UIimageView的也一樣,這是關(guān)鍵點(diǎn)之一。
另一個(gè)關(guān)鍵點(diǎn)是在滑動(dòng)的時(shí)候設(shè)置偏移量,YLMoveImageView中要設(shè)置一個(gè)SET方法,如下所示:
? ? ?var image_offset:CGFloat? {
? ? ? ? get{
? ? ? ? ? ? return_image_offset
? ? ? ? }
? ? ? ? set(image_offset) {
? ? ? ? ? ? _image_offset= image_offset
? ? ? ? ? ? varnew_y = -(_image_offset!/2.0);
? ? ? ? ? ? ifnew_y >0{
? ? ? ? ? ? ? ? new_y =0
? ? ? ? ? ? }? elseifnew_y?
? ? ? ? ? ? ? ? new_y =self.frame.height-self.m_imageView.frame.height
? ? ? ? ? ? }
? ? ? ? ? ? self.m_imageView.frame=CGRect.init(x:0, y: new_y, width:self.m_imageView.frame.size.width, height:self.m_imageView.frame.size.height)
? ? ? ? }
?? ?}
記得最好定義一個(gè)變量:var _image_offset:CGFloat?,等同于OC中的Set方法的實(shí)現(xiàn)。
在外部視圖控制器中,代碼如下:
funcscrollViewDidScroll(_scrollView:UIScrollView) {
? ? ? ? self.m_moveImage!.image_offset= scrollView.contentOffset.y
? ? }
到這里基本上就能實(shí)現(xiàn)那個(gè)動(dòng)效了,不得不吐槽一下簡(jiǎn)書,寫文章的時(shí)候竟然沒找到附件在哪里上傳,需要完整demo的可以到這里下載。