重写 View 的 Touch 方法,实现一个酷炫的九宫格图片
生活随笔
收集整理的這篇文章主要介紹了
重写 View 的 Touch 方法,实现一个酷炫的九宫格图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前幾天翻看代碼庫,發現一個之前寫過的一個有意思的小玩意,共享給大家?
廢話不多說,上圖,先看看效果
photosView.gif
怎么樣,是不是還蠻有意思呢?
實現起來非常簡單,我們只需要重寫幾個 View 的 touch 方法
//觸摸開始 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ ? ?if ( [[[touches allObjects]lastObject] view]==self) {? ? ? ?return;//這個地方demo里面沒有加判斷,可能會有崩潰現象,加上就好了
? ?} ? ?
? ?//獲取觸摸點 ? ? UITouch *touch = [touches anyObject]; ? ?CGPoint point = [touch locationInView:self]; ? ?//當前點擊到的圖片的下標小于圖片數組的元素個數 ? ? _selectIndex = [self itemIndexWithPoint:point]; ? ?if (_selectIndex < self.itemArray.count) { ? ? ? ?UIImageView *item = self.itemArray[_selectIndex]; ? ? ? ?//拿到最上層 ? ? ? ? [self bringSubviewToFront:item]; ? ? ? ?//動畫效果 ? ? ? ? [UIView animateWithDuration:0.3 animations:^{ ? ? ? ? ? ?//改變當前選中圖片視圖的大小和位置 ? ? ? ? ? ? item.center = point; ? ? ? ? ? ? item.transform = CGAffineTransformMakeScale(1.2, 1.2); ? ? ? ? ? ? item.alpha = 0.8; ? ? ? ? }]; ? ? } ? }
在觸摸一開始,我們先判定當前觸摸的點是在哪一張圖片上,獲得這張圖片的下標,并設置為選中下標,然后改變當前圖片的位置(中心移動到觸摸點)和大小(放大效果)。
//觸摸移動 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ ? ?//獲取觸摸點 ? ? UITouch *touch = [touches anyObject]; ? ?CGPoint point = [touch locationInView:self]; ? ?//獲取當前觸摸點位置下標 ? ? NSInteger index = [self itemIndexWithPoint:point]; ? ?if (_selectIndex < self.itemArray.count) { ? ? ? ?UIImageView *item = self.itemArray[_selectIndex]; ? ? ? ? item.center = point; ? ? ? ?if (index < self.itemArray.count && index != _selectIndex) { ? ? ? ? ? ?//當前點位置所屬下標與選中下標不同 ? ? ? ? ? ? //將兩個圖片分別在數據源數組和子視圖數組中移除 ? ? ? ? ? ? UIImage *image = _dataList[_selectIndex]; ? ? ? ? ? ? [_dataList removeObjectAtIndex:_selectIndex]; ? ? ? ? ? ? [self.itemArray removeObjectAtIndex:_selectIndex]; ? ? ? ? ? ?//重新插入到指定位置 ? ? ? ? ? ? [_dataList insertObject:image atIndex:index]; ? ? ? ? ? ? [self.itemArray insertObject:item atIndex:index]; ? ? ? ? ? ?//重新記錄選中下標 ? ? ? ? ? ? _selectIndex = index; ? ? ? ? ? ?//重新布局 ? ? ? ? ? ? [self restartMakeItemFram]; ? ? ? ? } ? ? } ? }然后在觸摸移動方法中再次判定當前觸摸點所在的圖片下標,然后比較選中下標與當前下標,如果不相同,就交換兩張圖片的位置。
//觸摸結束 - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ ? ?if (_selectIndex < _itemArray.count) { ? ? ? ?UIImageView *item = _itemArray[_selectIndex]; ? ? ? ?//還原操作 ? ? ? ? [UIView animateWithDuration:0.3 animations:^{ ? ? ? ? ? ? item.transform = CGAffineTransformIdentity; ? ? ? ? ? ? item.alpha = 1; ? ? ? ? ? ? item.frame = [self makeFrameWithIndex:(int)_selectIndex]; ? ? ? ? }]; ? ? } ? }最后,在觸摸結束方法中還原選中圖片的大小,重新計算它的位置
是不是很簡單呢?下面附上 Demo 的地址
Demo點這里~點這里:https://github.com/li1024316925/PhotosView
?
文/i_have_an_Apple(簡書作者)
原文鏈接:http://www.jianshu.com/p/309cd2886e05
著作權歸作者所有,轉載請聯系作者獲得授權,并標注“簡書作者”。
總結
以上是生活随笔為你收集整理的重写 View 的 Touch 方法,实现一个酷炫的九宫格图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JSP中四种传递参数的方法
- 下一篇: Spring Data MongoDB