-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathattribtext2.py
46 lines (39 loc) · 1.42 KB
/
attribtext2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# coding: utf-8
# set attributed text dor existing textview
# same works for Label, except dont need to set allowsAttributedTextEditing, or call on main thread
from objc_util import *
import re
mystr='''here are some colors:
red, yellow, blue, magenta, black, cyan
this is also editable
'''
mystro=ObjCClass('NSMutableAttributedString').alloc().initWithString_(mystr)
UIColor=ObjCClass('UIColor')
colors={'red': UIColor.redColor(),
'green':UIColor.greenColor(),
'blue':UIColor.blueColor(),
'cyan':UIColor.cyanColor(),
'magenta':UIColor.magentaColor(),
'black':UIColor.blackColor(),
'yellow':UIColor.yellowColor()}
# go through each thing i want to highlight, and addAttribute to that range
for k,color in colors.items():
sre=re.finditer(k,mystr)
for m in sre:
st,end=m.span()
l=end-st
mystro.addAttribute_value_range_('NSBackgroundColor',color,NSRange(st,l))
f=ObjCClass('UIFont').fontWithName_size_('Courier',15)
mystro.addAttribute_value_range_(ObjCInstance(c_void_p.in_dll(c,'NSFontAttributeName')),f,NSRange(st,l))
# setup views
import ui
v=ui.View(bg_color='white',frame=(0,0,300,300))
tv=ui.TextView(flex='wh',frame=v.bounds)
v.add_subview(tv)
v.present('sheet')
#set up objc instance
tvo=ObjCInstance(tv)
def setAttribs():
tvo.setAllowsEditingTextAttributes_(True)
tvo.setAttributedText_(mystro)
on_main_thread(setAttribs)() #apparently this must be called on main thread for textview