UI控件筆記

  • UILabel
  • UIViewController
  • UITextField
  • UIScrollView
  • UIImage
  • UIWindow
  • UIView
  • UITableView
  • UIMenuController
  • UINavigation
  • UICollectionViewFlowLayout
  • UICollectionView
  • UITextView

  • UILabel
    self.textLabel.highlighted = YES;//設置label高亮
    self.textLabel.highlightedTextColor = [UIColor grayColor];//label高亮狀態(tài)下字體顏色

  • UIViewController
    1.automaticallyAdjustsScrollViewInsets
    /automaticallyAdjustsScrollViewInsets根據(jù)按所在界面的status bar幅慌,navigationbar意荤,
    與tabbar的高度焊虏,自動調(diào)整scrollview的 inset,設置為no宏娄,不讓viewController調(diào)整。
    /
    self.automaticallyAdjustsScrollViewInsets = NO;

    2.UIViewController的presentedViewController劫乱,presentingViewController和parentViewController三個屬性
      轉自:http://www.th7.cn/Program/IOS/201507/517610.shtml
    
      presentedViewController:The view controller that is presented by this view controlller(read-only),被本視圖控制器present出來的的視圖控制器(只讀)
      presentingViewController:The view controller that presented this view controller. (read-only)箍鼓,present出來本視圖控制器的視圖控制器(只讀)
      parentViewController:The parent view controller of the recipient(容器). (read-only)
      
      有ViewControllerA和ViewControllerB相赁,在A里使用presentViewController:animated:completion: 方法present視圖控制器B(如下):
    
      ViewControllerB *viewb = [[ViewControllerBalloc] init];
      [selfpresentViewController:viewb animated:YEScompletion:nil];
      NSLog(@"self.presentedViewController:     %@",self.presentedViewController);
      NSLog(@"self.presentingViewController:    %@",self.presentingViewController);
      NSLog(@"self.parentViewController:        %@",self.parentViewController);
    
      NSLog(@"viewb.presentedViewController:    %@", viewb.presentedViewController);
      NSLog(@"viewb.presentingViewController:   %@", viewb.presentingViewController);
      NSLog(@"viewb.parentViewController:       %@", viewb.parentViewController);
      
      打印結果為:
      2015-07-30 10:38:45.923 PresentDemo[1518:85346] self.presentedViewController:     <ViewControllerB: 0x7ff6c974a440>
      2015-07-30 10:38:45.924 PresentDemo[1518:85346] self.presentingViewController:    (null)
      2015-07-30 10:38:45.924 PresentDemo[1518:85346] self.parentViewController:        (null)
      
      2015-07-30 10:38:45.924 PresentDemo[1518:85346] viewb.presentedViewController:    (null)
      2015-07-30 10:38:45.924 PresentDemo[1518:85346] viewb.presentingViewController:   <ViewController: 0x7ff6c9729e40>
      2015-07-30 10:38:45.924 PresentDemo[1518:85346] viewb.parentViewController:       (null)
      
      視圖控制器B被本視圖控制器(A)present相寇,所以A的presentedViewController是ViewControllerB,B的presentingViewController是ViewController(即A)
    

  • UITextField
    // 設置光標顏色
    self.tintColor = [UIColor whiteColor];
    // 修改占位文字顏色
    [self setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

  • UIScrollView
    // 設置滾動條的內(nèi)邊距等于contentInset
    vc.tableView.scrollIndicatorInsets = vc.tableView.contentInset;

  • UIImage
    1.把圖片寫入相冊
    -(IBAction)save {
    if (self.imageView.image == nil) {
    return;
    }
    // 將圖片寫入相冊
    UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }

        -(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
        {
           if (error) {
                NSLog(@"保存失敗!");
            } else {
                NSLog(@"保存成功!");
            }
       }
     2.圖片圓形切圖
    @implementation UIImage (Extension)
     -(UIImage *)circleImage
    {
      // NO代表透明
      UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
      
      // 獲得上下文
      CGContextRef ctx = UIGraphicsGetCurrentContext();
      
      // 添加一個圓
      CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
      CGContextAddEllipseInRect(ctx, rect);
      
      // 裁剪
      CGContextClip(ctx);
      
      // 將圖片畫上去
      [self drawInRect:rect];
      
      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
      
      UIGraphicsEndImageContext();
      
      return image;
    }
    

  • UIWindow
    keyWindow:一個窗口當前能接受鍵盤和非觸摸事件時钮科,便被認為是主窗口唤衫。而觸摸事件則被投遞到觸摸發(fā)生的窗口,沒有相應坐標值的事件被投遞到主窗口
    绵脯。同一時刻只有一個窗口是主窗口佳励。
    UIWindow還定義了以下通知:
    · UIWindowDidBecomeVisibleNotification
    · UIWindowDidBecomeHiddenNotification
    · UIWindowDidBecomeKeyNotification
    · UIWindowDidResignKeyNotification
    .每當應用窗口發(fā)生編程變化時,UIWindow通知就會被投遞蛆挫。例如赃承,當你的應用顯示或者隱藏一個窗口時,UIWindowDidBecomeVisibleNotification和
    UIWindowDidBecomeHiddenNotification通知相應地就會被投遞悴侵。值得注意的是瞧剖,當應用轉移到后臺時,這些通知不會被投遞:即便應用轉到后臺時可免,
    窗口不會顯示抓于,窗口在應用的上下文中仍然被認為是可見的。
    .大多數(shù)應用不需要處理UIWindowDidBecomeVisibleNotification和UIWindowDidBecomeHiddenNotification通知浇借,很少有應用擁有一個以上窗口捉撮。
    .UIWindowDidBecomeKeyNotification 和 UIWindowDidResignKeyNotification能幫助你跟蹤應用窗口何時是主窗口,何時不是妇垢。
    當你通過顯示一個輸入配件視圖來或者用戶輸入時巾遭,你也許需要知道一個窗口是不是主窗口。

      1.自定義window
      //窗口級別: UIWindowLevelNormal < UIWindowLevelStatusBar < UIWindowLevelAlert
      UIWindow *window;
      window = [[UIWindow alloc] init];
      window.rootViewController = [UIViewController new];//ios需要設置根控制器
      window.frame = CGRectMake(0, 0, 375, 20);
      window.backgroundColor = [UIColor yellowColor];
      window.windowLevel = UIWindowLevelStatusBar;
      //顯示窗口
      window.hidden = NO;
      //成為主窗口并顯示
      //[window makeKeyAndVisible];
      2.設置狀態(tài)欄顏色
      //設置info.plist 
      View controller-based status bar appearance = NO//不讓控制器控制狀態(tài)欄
      [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;//設置全局狀態(tài)欄
      如果設置info.plist View controller-based status bar appearance = YES//讓控制器設置狀態(tài)欄
      /**
       * 讓當前控制器對應的狀態(tài)欄是白色
       */
      -(UIStatusBarStyle)preferredStatusBarStyle
      {
          return UIStatusBarStyleLightContent;
      }
      狀態(tài)欄由最上面的window的根控制器控制修己。
     // 更新狀態(tài)欄(self是控制器)
     [self setNeedsStatusBarAppearanceUpdate];
     3.判斷view是否在主窗口顯示
     @implementation UIView (XMGExtension)
      - (BOOL)isShowingOnKeyWindow
      {
          // 主窗口
          UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
          
          // 以主窗口左上角為坐標原點, 計算self的矩形框
          CGRect newFrame = [keyWindow convertRect:self.frame fromView:self.superview];
          CGRect winBounds = keyWindow.bounds;
          
          // 主窗口的bounds 和 self的矩形框 是否有重疊
          BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);
          
          return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects;
      }
    

  • UIView
    1.autoresizingMask
    //在 UIView 中有一個autoresizingMask的屬性恢总,它對應的是一個枚舉的值(如下),屬性的意思就是自動調(diào)整子控件與父控件中間的位置睬愤,寬高片仿。
    enum {
    UIViewAutoresizingNone = 0,
    UIViewAutoresizingFlexibleLeftMargin = 1 << 0,
    UIViewAutoresizingFlexibleWidth = 1 << 1,
    UIViewAutoresizingFlexibleRightMargin = 1 << 2,
    UIViewAutoresizingFlexibleTopMargin = 1 << 3,
    UIViewAutoresizingFlexibleHeight = 1 << 4,
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
    };
    /*
    UIViewAutoresizingNone就是不自動調(diào)整。
    UIViewAutoresizingFlexibleLeftMargin 自動調(diào)整與superView左邊的距離尤辱,保證與superView右邊的距離不變砂豌。
    UIViewAutoresizingFlexibleRightMargin 自動調(diào)整與superView的右邊距離,保證與superView左邊的距離不變光督。
    UIViewAutoresizingFlexibleTopMargin 自動調(diào)整與superView頂部的距離阳距,保證與superView底部的距離不變。
    UIViewAutoresizingFlexibleBottomMargin 自動調(diào)整與superView底部的距離结借,也就是說筐摘,與superView頂部的距離不變。
    UIViewAutoresizingFlexibleWidth 自動調(diào)整自己的寬度,保證與superView左邊和右邊的距離不變咖熟。
    UIViewAutoresizingFlexibleHeight 自動調(diào)整自己的高度圃酵,保證與superView頂部和底部的距離不變。
    UIViewAutoresizingFlexibleLeftMargin |UIViewAutoresizingFlexibleRightMargin 自動調(diào)整與superView左邊的距離馍管,保證與左邊的距離和右邊的距離和原來距左邊和右邊的距離的比例不變郭赐。比如原來距離為20,30确沸,調(diào)整后的距離應為68捌锭,102,即68/20=102/30罗捎。
    */
    2.setNeedsDisplay和setNeedsLayout
    UIView的setNeedsDisplay和setNeedsLayout方法观谦。首先兩個方法都是異步執(zhí)行的。而setNeedsDisplay會調(diào)用 自動調(diào)用drawRect方法宛逗,
    這樣可以拿到UIGraphicsGetCurrentContext坎匿,就可以畫畫了。而setNeedsLayout 會默認調(diào)用layoutSubViews雷激,就可以處理子視圖中的一些數(shù)據(jù)。
    宗上所訴告私,setNeedsDisplay方便繪圖屎暇,而layoutSubViews方便出來數(shù)據(jù)

      layoutSubviews在以下情況下會被調(diào)用:
      1、init初始化不會觸發(fā)layoutSubviews驻粟。
      2根悼、addSubview會觸發(fā)layoutSubviews。
      3蜀撑、設置view的Frame會觸發(fā)layoutSubviews挤巡,當然前提是frame的值設置前后發(fā)生了變化。
      4酷麦、滾動一個UIScrollView會觸發(fā)layoutSubviews矿卑。
      5、旋轉Screen會觸發(fā)父UIView上的layoutSubviews事件沃饶。
      6母廷、改變一個UIView大小的時候也會觸發(fā)父UIView上的layoutSubviews事件。
      7糊肤、直接調(diào)用setLayoutSubviews琴昆。
      
      drawRect在以下情況下會被調(diào)用:
      1、如果在UIView初始化時沒有設置rect大小馆揉,將直接導致drawRect不被自動調(diào)用业舍。drawRect調(diào)用是在Controller->loadView, Controller->viewDidLoad 兩方法之后掉用的.所以不用擔心在控制器中,這些View的drawRect就開始畫了.這樣可以在控制器中設置一些值給View(如果這些View draw的時候需要用到某些變量值).
      2、該方法在調(diào)用sizeToFit后被調(diào)用,所以可以先調(diào)用sizeToFit計算出size舷暮。然后系統(tǒng)自動調(diào)用drawRect:方法态罪。
      3、通過設置contentMode屬性值為UIViewContentModeRedraw脚牍。那么將在每次設置或更改frame的時候自動調(diào)用drawRect:向臀。
      4、直接調(diào)用setNeedsDisplay诸狭,或者setNeedsDisplayInRect:觸發(fā)drawRect:券膀,但是有個前提條件是rect不能為0。
      以上1,2推薦驯遇;而3,4不提倡
      
      drawRect方法使用注意點:
      1、若使用UIView繪圖叉庐,只能在drawRect:方法中獲取相應的contextRef并繪圖舒帮。如果在其他方法中獲取將獲取到一個 invalidate的ref并且不能用于畫圖。drawRect:方法不能手動顯示調(diào)用陡叠,必須通過調(diào)用setNeedsDisplay 或者 setNeedsDisplayInRect玩郊,讓系統(tǒng)自動調(diào)該方法。
      2枉阵、若使用calayer繪圖译红,只能在drawInContext: 中(類似于drawRect)繪制,或者在delegate中的相應方法繪制兴溜。同樣也是調(diào)用setNeedDisplay等間接調(diào)用以上方法
      3侦厚、若要實時畫圖,不能使用gestureRecognizer拙徽,只能使用touchbegan等方法來掉用setNeedsDisplay實時刷新屏幕
    

  • UITableView
    1.
    // cell的高度設置,cell的xib內(nèi)容已經(jīng)確定,ios8以后才支持
    self.tableView.estimatedRowHeight = 44;//初始化高度
    self.tableView.rowHeight = UITableViewAutomaticDimension;//計算高度
    2.
    // 去掉分割線
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    3.
    // 內(nèi)邊距
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    4.
    cell.accessoryType = UITableViewCellAccessoryNone;//cell沒有任何的樣式
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右邊有一個小箭頭刨沦,距離右邊有十幾像素;
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;//cell右邊有一個藍色的圓形button膘怕;
    cell.accessoryType = UITableViewCellAccessoryCheckmark;//cell右邊的形狀是對號想诅;

  • UIMenuController
    UILabel實現(xiàn)復制剪切功能
7DBEF01C-5643-4F95-83A3-B0DBDDE4F9EB.png
    #import <UIKit/UIKit.h>
    @interface XXLabel : UILabel
    @end
    @implementation XXLabel
    - (void)awakeFromNib
    {
        [self setup];
    }
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self setup];
        }
        return self;
    }
    
    - (void)setup
    {
        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick)]];
    }
    
    /**
     * 讓label有資格成為第一響應者
     */
    - (BOOL)canBecomeFirstResponder
    {
        return YES;
    }
    
    /**
     * label能執(zhí)行哪些操作(比如copy, paste等等)
     * @return  YES:支持這種操作
     */
    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
    {
        if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:)) return YES;
        
        return NO;
    }
    
    - (void)cut:(UIMenuController *)menu
    {
        // 將自己的文字復制到粘貼板
        [self copy:menu];
        
        // 清空文字
        self.text = nil;
    }
    
    - (void)copy:(UIMenuController *)menu
    {
        // 將自己的文字復制到粘貼板
        UIPasteboard *board = [UIPasteboard generalPasteboard];
        board.string = self.text;
    }
    
    - (void)paste:(UIMenuController *)menu
    {
        // 將粘貼板的文字 復制 到自己身上
        UIPasteboard *board = [UIPasteboard generalPasteboard];
        self.text = board.string;
    }
    
    - (void)labelClick
    {
        // 1.label要成為第一響應者(作用是:告訴UIMenuController支持哪些操作, 這些操作如何處理)
        [self becomeFirstResponder];
        
        // 2.顯示MenuController
        UIMenuController *menu = [UIMenuController sharedMenuController];
        // targetRect: MenuController需要指向的矩形框
        // targetView: targetRect會以targetView的左上角為坐標原點
        [menu setTargetRect:self.bounds inView:self];
        //    [menu setTargetRect:self.frame inView:self.superview];
        [menu setMenuVisible:YES animated:YES];
    }
    @end

UILabel實現(xiàn)彈出自定義功能

6D53A983-44A2-44BC-B2C5-A176D17B36F5.png
    #import "XXLabel.h"
    @interface XXLabel : UILabel
    @end
    @implementation XXLabel
    - (void)awakeFromNib
    {
        [self setup];
    }
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self setup];
        }
        return self;
    }
    
    - (void)setup
    {
        self.userInteractionEnabled = YES;
    }
    
    /**
     * 讓label有資格成為第一響應者
     */
    - (BOOL)canBecomeFirstResponder
    {
        return YES;
    }
    
    /**
     * label能執(zhí)行哪些操作(比如copy, paste等等)
     * @return  YES:支持這種操作
     */
    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
    {
        return NO;
    }
    @end


    #import "ViewController.h"
    #import "XXLabel.h"
    @interface ViewController ()
    @property (weak, nonatomic) IBOutlet UIWebView *webView;
    @property (weak, nonatomic) IBOutlet XXLabel *label;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        //    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
        [self.webView loadHTMLString:@"<div style=\"color:red;\">哈哈哈哈</div>" baseURL:nil];
        
        [self.label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick)]];
    }
    
    - (void)labelClick
    {
        // 1.label要成為第一響應者(作用是:告訴UIMenuController支持哪些操作, 這些操作如何處理)
        [self.label becomeFirstResponder];
        
        // 2.顯示MenuController
        UIMenuController *menu = [UIMenuController sharedMenuController];
        
        // 添加MenuItem, 要添加到控制器
        UIMenuItem *ding = [[UIMenuItem alloc] initWithTitle:@"頂" action:@selector(ding:)];
        UIMenuItem *replay = [[UIMenuItem alloc] initWithTitle:@"回復" action:@selector(replay:)];
        UIMenuItem *report = [[UIMenuItem alloc] initWithTitle:@"舉報" action:@selector(report:)];
        menu.menuItems = @[ding, replay, report];
        
        [menu setTargetRect:self.label.bounds inView:self.label];
        [menu setMenuVisible:YES animated:YES];
    }
    
    - (void)ding:(UIMenuController *)menu
    {
        NSLog(@"%s %@", __func__ , menu);
    }
    
    - (void)replay:(UIMenuController *)menu
    {
        NSLog(@"%s %@", __func__ , menu);
    }
    
    - (void)report:(UIMenuController *)menu
    {
        NSLog(@"%s %@", __func__ , menu);
    }
    @end

  • UINavigation

      + (id)appearanceWhenContainedIn:(Class <>)ContainerClass,...
      這個方法可設置某個類的改變:例如:設置UIBarButtonItem 在UINavigationBar、UIPopoverController淳蔼、UITabbar中的效果侧蘸。就可以這樣寫
      [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], [UIPopoverController class],[UITabbar class] nil] setTintColor:myPopoverNavBarColor];
    
    1.設置Navi的item文字屬性
      //UIBarButtonItem *item = [UIBarButtonItem appearance];//設置navi全局
      NSMutableDictionary *itemAttrs = [NSMutableDictionary dictionary];
      itemAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
      itemAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:11];
      itemAttrs[NSForegroundColorAttributeName] = [UIColor greenColor];
      [self.navigationItem.rightBarButtonItem setTitleTextAttributes:itemAttrs forState:UIControlStateNormal];
      
      // 強制刷新
      [self.navigationController.navigationBar layoutIfNeeded];
    2.自定義navi左側按鈕,返回側滑失效
      self.interactivePopGestureRecognizer.delegate = nil;//設置代理為空
    

  • UICollectionViewFlowLayout
    流水中間變大布局
    @interface XXXLineLayout : UICollectionViewFlowLayout
    @end
    @implementation XXXLineLayout

      - (instancetype)init
      {
          if (self = [super init]) {
          }
          return self;
      }
      
      /**
       * 當collectionView的顯示范圍發(fā)生改變的時候,是否需要重新刷新布局
       * 一旦重新刷新布局鹉梨,就會重新調(diào)用下面的方法:
       1.prepareLayout
       2.layoutAttributesForElementsInRect:方法
       */
      - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
      {
          return YES;
      }
      
      /**
       * 用來做布局的初始化操作(不建議在init方法中進行布局的初始化操作)
       */
      - (void)prepareLayout
      {
          [super prepareLayout];
          
          // 水平滾動
          self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
          
          // 設置內(nèi)邊距
          CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
          self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
      }
      
      /**
       UICollectionViewLayoutAttributes *attrs;
       1.一個cell對應一個UICollectionViewLayoutAttributes對象
       2.UICollectionViewLayoutAttributes對象決定了cell的frame
       */
      /**
       * 這個方法的返回值是一個數(shù)組(數(shù)組里面存放著rect范圍內(nèi)所有元素的布局屬性)
       * 這個方法的返回值決定了rect范圍內(nèi)所有元素的排布(frame)
       */
      - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
      {
          // 獲得super已經(jīng)計算好的布局屬性
          NSArray *array = [super layoutAttributesForElementsInRect:rect];
          
          // 計算collectionView最中心點的x值
          CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
          
          // 在原有布局屬性的基礎上讳癌,進行微調(diào)
          for (UICollectionViewLayoutAttributes *attrs in array) {
              // cell的中心點x 和 collectionView最中心點的x值 的間距
              CGFloat delta = ABS(attrs.center.x - centerX);
              
              // 根據(jù)間距值 計算 cell的縮放比例
              CGFloat scale = 1 - delta / self.collectionView.frame.size.width;
              
              // 設置縮放比例
              attrs.transform = CGAffineTransformMakeScale(scale, scale);
          }
          
          return array;
      }
      
      /**
       * 這個方法的返回值,就決定了collectionView停止?jié)L動時的偏移量
       */
      - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
      {
          // 計算出最終顯示的矩形框
          CGRect rect;
          rect.origin.y = 0;
          rect.origin.x = proposedContentOffset.x;
          rect.size = self.collectionView.frame.size;
          
          // 獲得super已經(jīng)計算好的布局屬性
          NSArray *array = [super layoutAttributesForElementsInRect:rect];
          
          // 計算collectionView最中心點的x值
          CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;
          
          // 存放最小的間距值
          CGFloat minDelta = MAXFLOAT;
          for (UICollectionViewLayoutAttributes *attrs in array) {
              if (ABS(minDelta) > ABS(attrs.center.x - centerX)) {
                  minDelta = attrs.center.x - centerX;
              }
          }
          
          // 修改原有的偏移量
          proposedContentOffset.x += minDelta;
          return proposedContentOffset;
      }
      
      @end
    

  • UICollectionView
    1.獲取當前現(xiàn)實在屏幕中的最后一個cell
    func save() {
    //保存圖片到本地

      //獲取當前現(xiàn)實在屏幕中的最后一個cell
      let index = collectionView.indexPathsForVisibleItems().last!
      let cell = collectionView.cellForItemAtIndexPath(index) as! YQTableViewCell
      let image = cell.iconView.image
      //第一個參數(shù)是圖片,第二個參數(shù)是當前控制器,第三個參數(shù)是當前控制器的didFinishSavingWithError:contextInfo:方法
      UIImageWriteToSavedPhotosAlbum(image!, self, #selector(YQTableViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
        }
      func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject){
      }
    
      2.跳到第0組的第10個cell
      節(jié)選自 http://my.oschina.net/u/2340880/blog/522613
      collectionVeiw.scrollToItemAtIndexPath(NSIndexPath(forItem: 10, inSection: 0),atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    
     //設置選中某一item存皂,并使視圖滑動到相應位置晌坤,scrollPosition是滑動位置的相關參數(shù)逢艘,如下:
      public struct UICollectionViewScrollPosition : OptionSetType {
          public init(rawValue: UInt)
          //無
          public static var None: UICollectionViewScrollPosition { get }
          
          // The vertical positions are mutually exclusive to each other, but are bitwise or-able with the horizontal scroll positions.
          // Combining positions from the same grouping (horizontal or vertical) will result in an NSInvalidArgumentException.
          //垂直布局時使用的 對應上中下
          public static var Top: UICollectionViewScrollPosition { get }
          public static var CenteredVertically: UICollectionViewScrollPosition { get }
          public static var Bottom: UICollectionViewScrollPosition { get }
          //水平布局時使用的  對應左中右
          // Likewise, the horizontal positions are mutually exclusive to each other.
          public static var Left: UICollectionViewScrollPosition { get }
          public static var CenteredHorizontally: UICollectionViewScrollPosition { get }
          public static var Right: UICollectionViewScrollPosition { get }
      }
    

  • UITextView
    //1.UITextView插入圖片
    // 1.創(chuàng)建附件
    let attachment = NSTextAttachment()
    attachment.image = image
    // 設置了附件的大小
    attachment.bounds = CGRectMake(0, -4, 20, 20)

          // 2. 根據(jù)附件創(chuàng)建屬性字符串
          let imageText = NSAttributedString(attachment: attachment)
          
          // 3.拿到當前所有的內(nèi)容
          let strM = NSMutableAttributedString(attributedString: self.textView.attributedText)
          
          // 4.插入表情到當前光標所在的位置
          let range = self.textView.selectedRange
          strM.replaceCharactersInRange(range, withAttributedString: imageText)
          // 屬性字符串有自己默認的尺寸
          strM.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(19), range: NSMakeRange(range.location, 1))
          
          // 5.將替換后的字符串賦值給UITextView
          self.textView.attributedText = strM
          // 恢復光標所在的位置
          // 兩個參數(shù): 第一個是指定光標所在的位置, 第二個參數(shù)是選中文本的個數(shù)
          self.textView.selectedRange = NSMakeRange(range.location + 1, 0)
    
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市骤菠,隨后出現(xiàn)的幾起案子它改,更是在濱河造成了極大的恐慌,老刑警劉巖商乎,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件央拖,死亡現(xiàn)場離奇詭異,居然都是意外死亡鹉戚,警方通過查閱死者的電腦和手機鲜戒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來抹凳,“玉大人顷蟆,你說我怎么就攤上這事渺氧⌒刮保” “怎么了后控?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長幸冻。 經(jīng)常有香客問我粹庞,道長,這世上最難降的妖魔是什么洽损? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任信粮,我火速辦了婚禮,結果婚禮上趁啸,老公的妹妹穿的比我還像新娘。我一直安慰自己督惰,他們只是感情好不傅,可當我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著赏胚,像睡著了一般访娶。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上觉阅,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天崖疤,我揣著相機與錄音,去河邊找鬼典勇。 笑死劫哼,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的割笙。 我是一名探鬼主播权烧,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼眯亦,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了般码?” 一聲冷哼從身側響起妻率,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎板祝,沒想到半個月后宫静,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡券时,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年孤里,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片革为。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡扭粱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出震檩,到底是詐尸還是另有隱情琢蛤,我是刑警寧澤,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布抛虏,位于F島的核電站博其,受9級特大地震影響,放射性物質發(fā)生泄漏迂猴。R本人自食惡果不足惜慕淡,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望沸毁。 院中可真熱鬧峰髓,春花似錦、人聲如沸息尺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽搂誉。三九已至徐紧,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間炭懊,已是汗流浹背并级。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留侮腹,地道東北人嘲碧。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像凯旋,于是被迫代替她去往敵國和親呀潭。 傳聞我的和親對象是個殘疾皇子钉迷,可洞房花燭夜當晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容