swift:textEditorDemo一个简单的富文本编辑器

TextEditorDemo

swift:textEditorDemo一个简单的富文本编辑器

一个简单的富文本编辑器

(IPhone 5s Xcode 6.3 swift 1.2)

实现了一些基本功能,并解决了一些问题:

  1. 更改字体大小,粗体,下划线,斜体字。并进行了数据的存储 更多请查看网友StringX的文章:http://www.jianshu.com/p/ab5326850e74/comments/327660#comment-327660
  2. 在TextView中添加照片,以及照片存储
  3. 实现键盘隐藏和弹出
  4. 实现默认提示文字效果:点击进行编辑时提示文字自动消失
  5. 解决改变文字属性,TextView自动滑到顶部问题
  6. 让TextView滑到光标所在点
  7. 利用自动布局 实现点击按钮底部工具栏隐藏到右端 ps:没有动画效果。。
  8. 简单封装了提示文字的功能 更多请查看网友johnlui的开源项目:https://github.com/johnlui/SwiftNotice
  9. 设置点击隐藏导航栏,设置滑动隐藏导航栏
重要说明:

这个Demo可能还隐藏了一些BUG,如果你解决了希望能共享,谢谢!O(∩_∩)O~~
导入的两个framework是用于选取照片,以及拍照的
联系方式:
邮箱:lfb.cd@qq.com QQ:962429707
还有我的微博号:我的微博

项目地址

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

如果有更新微博上会发消息的:我的微博

效果浏览:

IMG_0926.PNG

(gif图片大约4MB):

myTest-1.gif

还有个gif太大了,传不了了。请移至github查看吧github地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容