標籤:ios swift 文本編輯 textview 資料庫
TextEditorDemo
swift:textEditorDemo一個簡單的富文字編輯器
一個簡單的富文字編輯器
(IPhone 5s Xcode 6.3 swift 1.2)
實現並解決了一些準系統:
- 更改字型大小,粗體,底線,斜體字。並進行了資料的儲存 更多請查看網友StringX的文章:http://www.jianshu.com/p/ab5326850e74/comments/327660#comment-327660
- 在TextView中添加照片,以及照片儲存
- 實現鍵盤隱藏和彈出
- 實現預設提示文字效果:點擊進行編輯時提示文字自動消失
- 解決改變文字屬性,TextView自動滑到頂部問題
- 讓TextView滑到游標所在點
- 利用自動布局 實現點擊按鈕底部工具列隱藏到右端 ps:沒有動畫效果。。
- 簡單封裝了提示文字的功能 更多請查看網友johnlui的開源項目:https://github.com/johnlui/SwiftNotice
設定點擊隱藏導覽列,設定滑動隱藏導覽列
重要說明:這個Demo還有一些BUG:建立新的一個文本就插入圖片,儲存時會崩掉。給已有文本添加圖片就可以正常儲存。我在網上到處找了好久也不知道怎麼解決,反正我覺得莫名其妙。。如果你解決了希望能共用,謝謝!O(∩_∩)O~~
匯入的兩個framework是用於選取照片,以及拍照的
連絡方式:
郵箱:[email protected] QQ:962429707
還有我的微博號:我的微博
by lifubing in CUIT
項目地址
github地址
如果有更新微博上會發訊息的:我的微博
1. 更改字型:
//更改字型大小:self.text.typingAttributes[NSFontAttributeName] = UIFont.systemFontOfSize((CGFloat)(self.fontSize))//底線:self.text.typingAttributes[NSUnderlineStyleAttributeName] = 1//粗體:self.text.typingAttributes[NSFontAttributeName] = UIFont.boldSystemFontOfSize((CGFloat)(self.fontSize))//斜體:text.typingAttributes[NSObliquenessAttributeName] = 0.5
2. 插入圖片:
/* //選取照片 */ @IBAction func photeSelect(sender: AnyObject) { self.text.resignFirstResponder() var sheet:UIActionSheet if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){ sheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil,otherButtonTitles: "從相簿選擇", "拍照") }else{ sheet = UIActionSheet(title:nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "從相簿選擇") } sheet.showInView(self.view) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { var sourceType = UIImagePickerControllerSourceType.PhotoLibrary if(buttonIndex != 0){ if(buttonIndex==1){ //相簿 sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.text.resignFirstResponder() }else{ sourceType = UIImagePickerControllerSourceType.Camera } let imagePickerController:UIImagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.allowsEditing = true //true為拍照、選擇完進入圖片編輯模式 imagePickerController.sourceType = sourceType self.presentViewController(imagePickerController, animated: true, completion: { }) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){ var string:NSMutableAttributedString string = NSMutableAttributedString(attributedString: self.text.attributedText) var img = info[UIImagePickerControllerEditedImage] as! UIImage img = self.scaleImage(img) var textAttachment= NSTextAttachment() textAttachment.image = img var textAttachmentString = NSAttributedString(attachment: textAttachment) var countString:Int = count(self.text.text) as Int string.insertAttributedString(textAttachmentString, atIndex: countString) //可以用這個函數實現 插入到游標所在點 ps:如果你實現了希望能共用 text.attributedText = string /* // */ //string.appendAttributedString(textAttachmentString) picker.dismissViewControllerAnimated(true, completion: nil) } func scaleImage(image:UIImage)->UIImage{ UIGraphicsBeginImageContext(CGSizeMake(self.view.bounds.size.width, image.size.height*(self.view.bounds.size.width/image.size.width))) image.drawInRect(CGRectMake(0, 0, self.view.bounds.size.width, image.size.height*(self.view.bounds.size.width/image.size.width))) var scaledimage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledimage }
3. 實現鍵盤隱藏和彈出
/* //此bool 標誌是為了讓鍵盤 出現和隱藏 成對出現,否則會出現跳出兩次的情況.我也只有用這樣的辦法解決 = = // ps:如果你有更好的解決辦法,希望能與我分享哦!上面有一個連絡方式的 */ var bool:Bool = true func handleKeyboardWillShowNotification(notification: NSNotification) { if bool { keyboardWillChangeFrameWithNotification(notification, showsKeyboard: true) println("---show") bool = !bool } } func handleKeyboardWillHideNotification(notification: NSNotification) { if !bool { keyboardWillChangeFrameWithNotification(notification, showsKeyboard: false) println("---hide") bool = !bool } } func keyboardWillChangeFrameWithNotification(notification: NSNotification, showsKeyboard: Bool) { println("4") let userInfo = notification.userInfo! let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue // Convert the keyboard frame from screen to view coordinates. let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let keyboardViewBeginFrame = view.convertRect(keyboardScreenBeginFrame, fromView: view.window) let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window) var originDelta = abs((keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y)) println("the origin:\(originDelta)") // The text view should be adjusted, update the constant for this constraint. if showsKeyboard { textViewBottomLayoutGuideConstraint.constant += (originDelta) self.toolBarLayOut.constant += originDelta }else { textViewBottomLayoutGuideConstraint.constant -= (originDelta) self.toolBarLayOut.constant -= originDelta } UIView.animateWithDuration(animationDuration, delay: 0, options: .BeginFromCurrentState, animations: { self.view.layoutIfNeeded() }, completion: nil) // Scroll to the selected text once the keyboard frame changes. self.text.scrollRangeToVisible(self.text.selectedRange) //讓TextView滑到游標所在地方 }
4. 實現預設提示文字效果:點擊進行編輯時提示文字自動消失
/* // 實現預設提示文字效果:點擊文字則會自動消失。 */ func textViewShouldBeginEditing(textView: UITextView) -> Bool { if !isThereHavedata { text.text = "" text.textColor = UIColor.blackColor() isThereHavedata = true } return true }
5. 解決改變文字屬性,TextView自動滑到頂部問題
self.text.layoutManager.allowsNonContiguousLayout = false //用於解決改變文字屬性,TextView自動滑到頂部問題####6.讓TextView滑到游標所在點 self.text.scrollRangeToVisible(self.text.selectedRange)####7.利用自動布局 實現點擊按鈕底部工具列隱藏到右端
@IBAction func toright(sender: UIBarButtonItem) { if self.toRight.constant < 0{ //簡單判斷左移還是右移 self.Toolbar.layer.cornerRadius = 22 //改成圓角 self.toRight.constant += (text.bounds.width - 10) sender.image = UIImage(named: "fa-left") //改變圖片 }else { self.Toolbar.layer.cornerRadius = 0 //恢複原來不是圓角那樣 self.toRight.constant -= (text.bounds.width - 10) sender.image = UIImage(named: "fa-right") }}
8.簡單封裝了提示文字的功能
//複製showtext.swift檔案到工程 Notice.showText("減小字型", fontsize: fontSize,obliqueness: 0)//彈出提示
9.設定點擊隱藏導覽列,設定滑動隱藏導覽列
self.navigationController?.hidesBarsOnTap = false //設定點擊隱藏導覽列,false為取消 self.navigationController?.hidesBarsOnSwipe = true //設定滑動隱藏導覽列
10.解決UITextView經常出現游標不在最下方的情況
/* 使用UITextView的時候經常出現游標不在最下方的情況。。。(iOS8) 解決方案: 1、首先去除所有的Padding: self.text.textContainerInset = UIEdgeInsetsZero self.text.textContainer.lineFragmentPadding = 0 2、然後在委託方法裡加上一行: func textViewDidChange(textView: UITextView) { self.text.scrollRangeToVisible(self.text.selectedRange) } ps:委託方法在最下邊。 */ self.text.textContainerInset = UIEdgeInsetsZero self.text.textContainer.lineFragmentPadding = 0
項目地址
github地址
https://github.com/lfb-cd/TextEditorDemo
如果有更新微博上會發訊息的:我的微博
效果瀏覽:
(gif圖片大約10MB):
textEditorDemo:基於swift的一個富文字編輯器