ios開發之Swift UIPasteboard剪貼簿的使用詳解(複製、粘貼文字和圖片)

來源:互聯網
上載者:User

UITextField、UITextView組件系統原生就支援文字的複製,但有時我們需要讓其他的一些組件也能實現複製功能,比如點擊複製UILabel上的文字、UIImageView中的圖片、UITableView裡儲存格的內容、或者點擊按鈕把文字或圖片自動複製到粘貼板中等等。
這些我們藉助 UIPasteboard 就可以實現。

一,將內容寫入到剪貼簿中

1,複製字串


UIPasteboard.generalPasteboard().string = "歡迎訪問 hangge.com"

2,複製字串數組


UIPasteboard.generalPasteboard().strings = ["hellow", "hangge.com"]

3,複製圖片


let image = UIImage(named: "logo.png")
UIPasteboard.generalPasteboard().image = image

4,複製位元據(NSData)


let path = NSBundle.mainBundle().pathForResource("logo", ofType: "png")!
let fileData = NSData(contentsOfFile: path)!
UIPasteboard.generalPasteboard().setData(fileData, forPasteboardType: "public.png")

註:從剪貼簿擷取位元據(NSData)


let myData = UIPasteboard.generalPasteboard().dataForPasteboardType("public.png")


二,常見組件增加複製功能

1,讓文字標籤(UILabel)支援複製功能

我們自訂一個可複製的標籤類 UICopyLabel(繼承UILabel),其內部能響應 Touch 事件並顯示複製菜單


import UIKit
 
class UICopyLabel: UILabel {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }
    
    func sharedInit() {
        userInteractionEnabled = true
        addGestureRecognizer(UILongPressGestureRecognizer(target: self,
            action: "showMenu:"))
    }
    
    func showMenu(sender: AnyObject?) {
        becomeFirstResponder()
        let menu = UIMenuController.sharedMenuController()
        if !menu.menuVisible {
            menu.setTargetRect(bounds, inView: self)
            menu.setMenuVisible(true, animated: true)
        }
    }
    
    //複製
    override func copy(sender: AnyObject?) {
        let board = UIPasteboard.generalPasteboard()
        board.string = text
        let menu = UIMenuController.sharedMenuController()
        menu.setMenuVisible(false, animated: true)
    }
    
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
    override func canPerformAction(action: Selector, withSender sender: AnyObject?)
        -> Bool {
        if action == "copy:" {
            return true
        }
        return false
    }
}

在這個文字標籤上長按後便可以複製其內容:

2,讓圖片控制項(UIImageView)支援複製、粘貼功能

我們自訂一個圖片控制項類 UICPImageView(繼承UIImageView),內部同樣添加Touch事件響應。該控制項不僅支援複製,還支援粘貼。

import UIKit
 
class UICPImageView: UIImageView {
 
    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedInit()
    }
    
    func sharedInit() {
        userInteractionEnabled = true
        addGestureRecognizer(UILongPressGestureRecognizer(target: self,
            action: "showMenu:"))
    }
    
    func showMenu(sender: AnyObject?) {
        becomeFirstResponder()
        let menu = UIMenuController.sharedMenuController()
        if !menu.menuVisible {
            menu.setTargetRect(bounds, inView: self)
            menu.setMenuVisible(true, animated: true)
        }
    }
    
    //複製
    override func copy(sender: AnyObject?) {
        let board = UIPasteboard.generalPasteboard()
        board.image = self.image
        let menu = UIMenuController.sharedMenuController()
        menu.setMenuVisible(false, animated: true)
    }
    
    //粘貼
    override func paste(sender: AnyObject?) {
        let board = UIPasteboard.generalPasteboard()
        self.image = board.image
        let menu = UIMenuController.sharedMenuController()
        menu.setMenuVisible(false, animated: true)
    }
    
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    
    override func canPerformAction(action: Selector, withSender sender: AnyObject?)
        -> Bool {
        if action == "copy:" {
            return true
        }else if action == "paste:" {
            return true
        }
        return false
    }
}

下面我們在介面上添加兩個 UICPImageView,我們可以把左邊控制項裡的圖片複製到右邊控制項中來,效果圖如下:

 

3,讓表格(UITableView)支援複製功能


import UIKit
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView:UITableView?
    var tableData = ["條目1", "條目2", "條目3", "條目4", "條目5", "條目6", "條目7"]
    
    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //建立表視圖
        self.tableView = UITableView(frame: self.view.frame, style:.Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        //建立一個重用的儲存格
        self.tableView!.registerClass(UITableViewCell.self,
            forCellReuseIdentifier: "SwiftCell")
        self.view.addSubview(self.tableView!)
    }
    
    func tableView(tableView: UITableView, performAction action: Selector,
        forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
            let board = UIPasteboard.generalPasteboard()
            board.string = tableData[indexPath.row]
    }
    
    func tableView(tableView: UITableView, canPerformAction action: Selector,
        forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
            if action == "copy:" {
                return true
            }
            return false
    }
    
    func tableView(tableView: UITableView,
        shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    
    //在本例中,只有一個分區
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }
    
    //返回表格行數(也就是返回控制項數)
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }
    
    //建立各單元顯示內容(建立參數indexPath指定的單元)
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        //為了提供表格顯示效能,已建立完成的單元需重複使用
        let identify:String = "SwiftCell"
        //同一形式的儲存格重複使用,在聲明時登入
        let cell = tableView.dequeueReusableCellWithIdentifier(identify,
            forIndexPath: indexPath) as UITableViewCell
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        cell.textLabel?.text = tableData[indexPath.row]
        return cell
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

長按某個儲存格即可複製這個儲存格內容:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.