omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    Welcome!

    This is the community forum for my apps Pythonista and Editorial.

    For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.


    Multicolor in TextView?

    Pythonista
    2
    2
    1610
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • monlie
      monlie last edited by

      I would like to write a simple editor of scheme to learning SICP with my iPad. So I need to highlight some characters (such as keywords and brackets) in TextView. But it seems like I could only set a global font color for it.

      1 Reply Last reply Reply Quote 0
      • cvp
        cvp last edited by ccc

        See and try sample of @JonB here
        It uses attributedText in Objective-C

        Sample based on this code

        # coding: utf-8
        # set attributed text dor existing textview
        # see JonB code at 
        #     https://github.com/jsbain/objc_hacks/blob/master/attribtext2.py
        import ui
        from objc_util import *
        
        class MyView(ui.View):
        	def __init__(self):
        		self.width = 300
        		self.height = 300
        		tv=ui.TextView(flex='wh',frame=self.bounds)
        		tv.delegate = self
        		self.add_subview(tv)
                tv.begin_editing()
        		
        		UIColor=ObjCClass('UIColor')
        		self.UIred = UIColor.redColor()
        		self.UIfont=ObjCClass('UIFont').fontWithName_size_('Courier',20)
        
        		#set up objc instance		
        		self.tvo=ObjCInstance(tv)
        		
        	def textview_did_change(self, textview):
        		self.stro=ObjCClass('NSMutableAttributedString').alloc().initWithString_( textview.text)
        		i = 0
        		st = textview.text.find('[',i)
        		l = 1
        		while st >= 0:					
        			self.stro.addAttribute_value_range_('NSBackgroundColor',self.UIred,NSRange(st,l))
        			self.stro.addAttribute_value_range_(ObjCInstance(c_void_p.in_dll(c,'NSFontAttributeName')),self.UIfont,NSRange(st,l))
        			self.setAttribs()
        			i = st + 1
        			st = textview.text.find('[',i)
        		
        	@on_main_thread
        	#apparently this must be called on main thread for textview
        	def setAttribs(self):
        		self.tvo.setAllowsEditingTextAttributes_(True)
        		self.tvo.setAttributedText_(self.stro)
        		
        v=MyView()
        v.present('sheet')
        

        It allows you to enter your text and it set the red color for all "[" found in it.

        1 Reply Last reply Reply Quote 0
        • First post
          Last post
        Powered by NodeBB Forums | Contributors