Texteditordemo: A rich text editor based on Swift

Source: Internet
Author: User

Texteditordemo

Swift:texteditordemo a simple Rich text editor

A simple Rich Text editor

(IPhone 5s Xcode 6.3 Swift 1.2)

Some basic features are implemented and resolved:

    1. Change font size, bold, underline, italic. And the storage of the data more please check the article of Netizen STRINGX: http://www.jianshu.com/p/ab5326850e74/comments/327660#comment-327660
    2. Add photos in TextView, and photo storage
    3. Implement keyboard hiding and Popup
    4. Implement default prompt text effect: Prompt text disappears automatically when you click to edit
    5. Resolve change Text properties, TextView Auto slide to top problem
    6. Let TextView slide to the point where the cursor is located
    7. Use automatic layout to achieve click Button Bottom toolbar hidden to right side PS: no animation effect.
    8. Simply encapsulates the function of the hint text more please see the Open source project of Netizen Johnlui: Https://github.com/johnlui/SwiftNotice
    9. Set Click to hide Navigation bar, set slide to hide navigation bar

      Important NOTES:

      This demo also has some bugs: Create a new text to insert the picture, the save will be collapsed. Add a picture to the existing text to save it as normal. I looked around the internet for a long time and do not know how to solve, anyway, I feel puzzled. If you solve the hope can be shared, thank you! O (∩_∩) o~~
      The two frameworks that are imported are for selecting photos, and for taking pictures of
      Contact information:
      Email: [Email protected] qq:962429707
      And my Weibo number: my Weibo.
      by lifubing in CUIT

Project Address

GitHub Address
If there is a message on the update Weibo: my Weibo

1. Change the font:
//Change font size: Self. Text. Typingattributes[Nsfontattributename] =Uifont. Systemfontofsize((CGFloat)( Self. FontSize))//underline: Self. Text. Typingattributes[Nsunderlinestyleattributename] =1//Bold: Self. Text. Typingattributes[Nsfontattributename] =Uifont. Boldsystemfontofsize((CGFloat)( Self. FontSize))//Italic:Text. Typingattributes[Nsobliquenessattributename] =0.5
2. Insert Picture:
    /*/SELECT Photo * /@IBAction func Photeselect (sender:anyobject) {self. Text. Resignfirstresponder() var sheet:uiactionsheet if (Uiimagepickercontroller. Issourcetypeavailable(Uiimagepickercontrollersourcetype. Camera) {sheet = Uiactionsheet (Title:nil, delegate:self, Cancelbuttontitle:"Cancel", Destructivebuttontitle:nil,otherbuttontitles:"Select from album","Take photos")}else{sheet = Uiactionsheet (Title:nil, delegate:self, Cancelbuttontitle:"Cancel", Destructivebuttontitle:nil, Otherbuttontitles:"Select from album")} sheet. Showinview(Self. View)} func Actionsheet (Actionsheet:uiactionsheet, Clickedbuttonatindex buttonindex:int) {var sourcetype = UI Imagepickercontrollersourcetype. Photolibraryif (buttonindex! =0) {if (buttonindex==1) {//album SourceType = Uiimagepickercontrollersourcetype. PhotolibrarySelf. Text. Resignfirstresponder()}else{sourcetype = Uiimagepickercontrollersourcetype. Camera} Let Imagepickercontroller:uiimagepickercontroller = Uiimagepickercontroller () Imagepickercontrolle R. Delegate= Self Imagepickercontroller. allowsediting= True//true to take pictures, select Finish to enter picture editing mode Imagepickercontroller. SourceType= SourceType Self. Presentviewcontroller(Imagepickercontroller, Animated:true, completion: {})}} func Imagepickercontroller (Picker:ui Imagepickercontroller, didfinishpickingmediawithinfo info: [Nsobject:anyobject]) {var string:nsmutableattributeds Tring 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)//You can use this function to implement the insertion to the point where the cursor is PS: If you realize that you want to share 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. Implement keyboard Hide and eject
     /*//This bool flag is for the keyboard to appear and hide in pairs appear, or there will be a jump two times. I only use this method to solve = =//PS: If you have a better solution, hope to share with me Oh! There is a contact on the above * /VarBOOL: Bool =trueFunc 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 screens 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 is adjusted, update the constant for this constraint.        ifShowskeyboard {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)//Let TextView slide to the cursor location}
4. Implement default prompt text effect: Prompt text disappears automatically when you click to edit
     /*    // 实现默认提示文字效果:点击文字则会自动消失。    */    func textViewShouldBeginEditing(textView: UITextView) -> Bool {        if !isThereHavedata {            text.text""            text.textColor = UIColor.blackColor()            true        }        returntrue    }
5. Resolve change text attribute, TextView auto slide to top problem
 Self.text  .layoutmanager  .allowsnoncontiguouslayout  = False//To resolve the change of text properties, TextView automatically slide to the top of the problem ### #6. Let TextView slide to the point where the cursor is located  self.text  .scrollrangetovisible  (Self.text  .selectedrange ) ### #7. Using Automatic Layout Implementation Click the button at the bottom of the toolbar to hide to the right side   
 @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. Simple encapsulation of the function of the hint text
    //复制showtext.swift文件到工程    Notice.showText("减小字体"0)//弹出提示
9. Set Click to hide Navigation bar, set slide to hide navigation bar
selffalse           //设置点击隐藏导航栏,false为取消    selftrue          //设置滑动隐藏导航栏
10. Solve Uitextview often appear the cursor is not at the bottom of the situation
/* UseUitextviewOften appear at the bottom of the cursor is not the case ... (iOS8) Workaround:1, first Remove allPadding: Self. Text.textcontainerinset =Uiedgeinsetszero                 Self. text.textContainer.lineFragmentPadding =0        2, and then add a line to the delegate method: Func Textviewdidchange (TextView: Uitextview) { Self. text.scrollrangetovisible ( Self. Text.selectedrange)}PS:The delegate method is at the bottom. */ Self. Text.textcontainerinset =Uiedgeinsetszero         Self. text.textContainer.lineFragmentPadding =0
Project Address

GitHub Address

Https://github.com/lfb-cd/TextEditorDemo

If there is a message on the update Weibo: my Weibo

Effect View:

(GIF image approx. 10MB):


Texteditordemo: A rich text editor based on Swift

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.