alert = UIAlertController.alertControllerWithTitle_message_preferredStyle_( ns('My Alert'), ns('My Message'), 1) alert_action_block = ObjCBlock(ok_pressed, None, [c_void_p]) default_action = UIAlertAction.actionWithTitle_style_handler_( ns('OK'), 0, None) alert.addAction_(default_action) ##rvc.presentModalViewController_animated_(alert, True) ## Stop Crashes retain_global(alert_action_block) def button_tapped(sender): super_view = sender.superview super_view_pntr = ObjCInstance(super_view) vc = SUIViewController.viewControllerForView_(super_view_pntr) vc.presentModalViewController_animated_(alert, True) view = ui.View(frame=(0, 0, 500, 500)) view.name = 'Demo' view.background_color = 'white' button = ui.Button(title='Tap me!') button.center = (view.width * 0.5, view.height * 0.5) button.flex = 'LRTB' button.action = button_tapped view.add_subview(button) view.present('sheet')
def screen(title='title'): button = ui.Button(title=title) button.action = lambda sender: sender.close() button.present(hide_title_bar=True) button.wait_modal()
def __init__(self): ui.ThinBoard.__init__(self) name = ui.TextLine() name.SetParent(self) name.SetDefaultFontName() name.SetOutline() name.Show() hpGauge = ui.Gauge() hpGauge.SetParent(self) hpGauge.MakeGauge(130, "red") hpGauge.Hide() closeButton = ui.Button() closeButton.SetParent(self) closeButton.SetUpVisual("d:/ymir work/ui/public/close_button_01.sub") closeButton.SetOverVisual("d:/ymir work/ui/public/close_button_02.sub") closeButton.SetDownVisual("d:/ymir work/ui/public/close_button_03.sub") closeButton.SetPosition(30, 13) hpGauge.SetPosition(175, 17) hpGauge.SetWindowHorizontalAlignRight() closeButton.SetWindowHorizontalAlignRight() closeButton.SetEvent(ui.__mem_func__(self.OnPressedCloseButton)) closeButton.Show() self.buttonDict = {} self.showingButtonList = [] for buttonName in self.BUTTON_NAME_LIST: button = ui.Button() button.SetParent(self) button.SetUpVisual("d:/ymir work/ui/public/small_thin_button_01.sub") button.SetOverVisual("d:/ymir work/ui/public/small_thin_button_02.sub") button.SetDownVisual("d:/ymir work/ui/public/small_thin_button_03.sub") button.SetWindowHorizontalAlignCenter() button.SetText(buttonName) button.Hide() self.buttonDict[buttonName] = button self.showingButtonList.append(button) self.buttonDict[localeInfo.TARGET_BUTTON_WHISPER].SetEvent(ui.__mem_func__(self.OnWhisper)) self.buttonDict[localeInfo.TARGET_BUTTON_EXCHANGE].SetEvent(ui.__mem_func__(self.OnExchange)) self.buttonDict[localeInfo.TARGET_BUTTON_FIGHT].SetEvent(ui.__mem_func__(self.OnPVP)) self.buttonDict[localeInfo.TARGET_BUTTON_ACCEPT_FIGHT].SetEvent(ui.__mem_func__(self.OnPVP)) self.buttonDict[localeInfo.TARGET_BUTTON_AVENGE].SetEvent(ui.__mem_func__(self.OnPVP)) self.buttonDict[localeInfo.TARGET_BUTTON_FRIEND].SetEvent(ui.__mem_func__(self.OnAppendToMessenger)) self.buttonDict[localeInfo.TARGET_BUTTON_FRIEND].SetEvent(ui.__mem_func__(self.OnAppendToMessenger)) self.buttonDict[localeInfo.TARGET_BUTTON_INVITE_PARTY].SetEvent(ui.__mem_func__(self.OnPartyInvite)) self.buttonDict[localeInfo.TARGET_BUTTON_LEAVE_PARTY].SetEvent(ui.__mem_func__(self.OnPartyExit)) self.buttonDict[localeInfo.TARGET_BUTTON_EXCLUDE].SetEvent(ui.__mem_func__(self.OnPartyRemove)) self.buttonDict[localeInfo.TARGET_BUTTON_INVITE_GUILD].SAFE_SetEvent(self.__OnGuildAddMember) self.buttonDict[localeInfo.TARGET_BUTTON_DISMOUNT].SAFE_SetEvent(self.__OnDismount) self.buttonDict[localeInfo.TARGET_BUTTON_EXIT_OBSERVER].SAFE_SetEvent(self.__OnExitObserver) self.buttonDict[localeInfo.TARGET_BUTTON_VIEW_EQUIPMENT].SAFE_SetEvent(self.__OnViewEquipment) self.buttonDict[localeInfo.TARGET_BUTTON_REQUEST_ENTER_PARTY].SAFE_SetEvent(self.__OnRequestParty) self.buttonDict[localeInfo.TARGET_BUTTON_BUILDING_DESTROY].SAFE_SetEvent(self.__OnDestroyBuilding) self.buttonDict[localeInfo.TARGET_BUTTON_EMOTION_ALLOW].SAFE_SetEvent(self.__OnEmotionAllow) self.buttonDict["VOTE_BLOCK_CHAT"].SetEvent(ui.__mem_func__(self.__OnVoteBlockChat)) self.name = name self.hpGauge = hpGauge self.closeButton = closeButton self.nameString = 0 self.nameLength = 0 self.vid = 0 self.eventWhisper = None self.isShowButton = False self.__Initialize() self.ResetTargetBoard()
@staticmethod def hit(uiobj, location): ''' check if location is inside uiobj's bounds''' if location[0] < 0 or location[1] < 0 or location[ 0] > uiobj.width or location[1] > uiobj.height: return False else: return True if __name__ == '__main__': v = TouchDispatcher(name='root') #populate some contents b = ui.Button(frame=(10, 10, 100, 100), bg_color='red', name='button1') b.title = 'press' t = ui.TextField(frame=(110, 10, 300, 50), bg_color='white') v.add_subview(t) def myaction(sender): pass #print sender.name,' pressed' b.action = myaction v.add_subview(b) #create a second dispatcher to demonstrate trickle down v2 = TouchDispatcher(name='second_view', bg_color='cyan') v2.frame = (200, 200, 300, 300) b = ui.Button(frame=(10, 10, 100, 100), bg_color='red', name='button2')
# coding: utf-8 # https://forum.omz-software.com/topic/2778/ui-view-present-popover-can-t-work-out-popover_location import ui def btn_action(sender): print sender f = (0,0,400, 800) pt = tuple(sender.center) v = ui.View(frame = f) loc = ui.convert_point(pt, sender, None) #loc = ui.convert_point(loc, None, v) v.present('popover', popover_location = tuple(loc) ) if __name__ == '__main__': f = (0,0,500,500) v = ui.View(frame = f) btn = ui.Button(frame = (100,100, 100, 32)) btn.border_width = .5 btn.action = btn_action btn.title = 'hello' v.add_subview(btn) v.present('sheet')
# 创建图层 view = ui.View( frame=(0, 0, 380, 120), background_color=(0.0, 0.0, 0.0, 0.1)) # 创建标签,用来展示更新状态 label = ui.Label( frame=(44, 0, 236, 120), flex='TLWH', font=('<System>', 18), number_of_lines=5, text_color='black', text=check()) # 将标签添加到图层 view.add_subview(label) # 创建按钮,用来触发无广告阅读界面 botton = ui.Button( frame=(336,40,40,40), action=botton_tapped, font=('<System>', 20), title='Read') # 将按钮添加到图层 view.add_subview(botton) # 显示界面 appex.set_widget_view(view) # 在 Pythonista 中运行,无广告阅读小说 else: read_action()
v = ui.View() v.background_color = '#fff' dice = Dice(5, 6) def hold_change(idx, held): if held: dice.hold(idx) else: dice.release(idx) x, y, w, h = v.frame dv = YahtzeeDiceView(frame=(5, 5, w - 10, 100)) dv.onholdchange = hold_change v.add_subview(dv) btn = ui.Button() btn.title = 'Roll' def rol(sender): btn.enabled = False dice.roll() dv.roll_to(dice) def re_enable_btn(): btn.enabled = True dv.onrollfinished = lambda: re_enable_btn() btn.action = rol btn.frame = (5, 100, w - 10, 80) btn.flex = 'W' v.add_subview(btn)
def out_callback(line): if 'Established control over the server. You have command access level' in line: start_button = ui.Dialog( ui.get_screen(), ui.Button('Touch to start game', callback)) start_button.back = callback ui.set(start_button, anim=False)
# https://forum.omz-software.com/topic/2513/getting-the-parent-of-a-dynamically-method-as-a-function/52 import ui def test_func(msg): ''' i would like to get a reference to the caller here being the btn. i am pretty sure the answer lies with the inspect module, but i cant figure it out. MAYBE, its even easier than that... well that would be great ''' print(msg) btn = ui.Button() btn.msg = test_func btn.msg('I am on to something...') #============================== import types class Extender(object): def __new__(cls, target_instance, *args, **kwargs): if isinstance(cls.__init__, types.MethodType): cls.__init__.__func__(target_instance, *args, **kwargs) extender_instance = super(Extender, cls).__new__(cls) for key in dir(extender_instance): if key.startswith('__'): continue
# sender is the button # could do the below line, maybe not so clear... so will write it out #the_value = int(sender.connected_label.text) lb = sender.connected_label # dynamically created attribute int_val = int(lb.text) the_value = int_val print(the_value) lb.text = str(the_value + sender.increment_value) f = (0, 0, 200, 200) v = ui.View(frame=f) v.bg_color = 'white' lb = ui.Label(frame=(10, 10, 100, 32)) lb.text = '1001' btn = ui.Button(frame=(10, lb.height + 30, 80, 32)) btn.title = 'Hit Me' btn.action = btn_action btn.border_width = .5 btn.corner_radius = 3 ''' very important, the 2 next lines of code are referencing attributes that dont exist in a ui.Button. They are created dynamically because you assign a value to them ( i think thats the right jargon) ''' btn.connected_label = lb btn.increment_value = 10 v.add_subview(btn) v.add_subview(lb) v.present('sheet')
lb1.tint_color = 'black' lb1.background_color = 'yellow' lb1.flex = 'WHLRTB' # Center text lb1.alignment = 1 v.add_subview(lb1) lb2 = ui.Label(frame=(32, 85, 350, 53)) lb2.font = ('<system-bold>', 22) lb2.text = 'Select A Date & Time' lb2.flex = 'WHLRTB' # Center text lb2.alignment = 1 v.add_subview(lb2) btn1 = ui.Button(frame=(32, 531, 350, 53)) btn1.font = ('<system-bold>', 16) btn1.title = 'Set To Current Date - Time' btn1.border_width = 2 btn1.corner_radius = 10 btn1.tint_color = 'black' btn1.background_color = '#7af685' btn1.flex = 'WHLRTB' btn1.action = set_current v.add_subview(btn1) btn2 = ui.Button(frame=(32, 592, 350, 53)) btn2.font = ('<system-bold>', 16) btn2.title = 'Done' btn2.border_width = 2 btn2.corner_radius = 10
url = f.commit() # on device 2 with cloud.File(url, 'r', encryptionKey='password') as f: console.hud_alert(f.read()) # ==================== # coding: utf-8 # Transfer images between devices # cloudInage.py import cloud, ui from PIL import Image # on device 1 ip = Image.open('iob:ios7_cloud_outline_256') with cloud.File('', 'wb', encryptionKey='password') as f: ip.save(f, ip.format) url = f.commit() # on device 2 with cloud.File(url, 'rb', encryptionKey='password') as f: ui.Button(image=ui.Image.from_data(f.read())).present() # ====================
c = '' # not 1st encode of a char #print(p,i,c,x,x_prev,cc) if (sender.title == 'speak') or (x == x_prev): cc = cc + c if p < (len(idxtopos) - 1): continue else: if ('spell' in sender.title) and (cc != ''): speak_or_spell('spell', cc) cc = c x_prev = x if sender.title == 'speak': speak_or_spell('speak', cc) b_speak = ui.Button() b_speak.frame = (10, 170, 60, 32) b_speak.title = 'speak' b_speak.border_width = 1 b_speak.border_color = 'blue' b_speak.corner_radius = 5 b_speak.action = b_speak_or_spell v.add_subview(b_speak) b_spell = ui.Button() b_spell.frame = (80, 170, 60, 32) b_spell.title = 'spell' b_spell.border_width = 1 b_spell.border_color = 'blue' b_spell.corner_radius = 5 b_spell.action = b_speak_or_spell
max = 20 def roll(sender): val = random.randint(min, max) sender.superview['result_label'].text = str(val) def reset(sender): sender.superview['result_label'].text = "" v = ui.View(frame=(0, 0, 300, 110)) label = ui.Label(frame=(150, 0, 140, 100), flex='lwh', font=('<System>', 50), alignment=ui.ALIGN_CENTER, name='result_label') v.add_subview(label) button = ui.Button(title='Roll d20', font=('<System>', 24), flex='lwh', action=roll, name='button_label') button.frame = (20, 25, 70, 50) v.add_subview(button) appex.set_widget_view(v)
# https://gist.github.com/jsbain/6fc02b7d75eb22111b826cfdb2394697 import ui from math import pi v = ui.View(frame=(0, 0, 576, 576)) v.bg_color = (1, 1, 1) N = 12 for i in range(0, N): a = ui.Button(image=ui.Image.named('iob:arrow_up_a_256')) a.height = a.width = 64 a.center = v.bounds.center() a.transform = ui.Transform.translation( 0, -(v.height / 2 - a.height / 2)).concat( ui.Transform.rotation(2. * pi * i / N)) v.add_subview(a) v.present('sheet')
def add_difficulty_button(self): def _callback(optionsPanel): change_difficulty(self.difficulty_button) self.difficulty_button = ui.Button('Default difficulty for new games: ' + features.get('app.difficulty'), functools.partial(_callback, self)) self.add(self.difficulty_button)
0.1)).concat(ui.Transform.translation(300, 300)) v.alpha = 0.1 v.hidden = False b2.hidden = True def a(): v.transform = ui.Transform() #default v.alpha = 1 def compl(): pass ui.animate(a, .3, completion=compl) v = ui.View(bg_color='#ffc280', frame=(0, 0, 200, 200)) v.add_subview(ui.TextView(name='text', frame=(20, 40, 60, 40))) v['text'].text = 'Click above' root = ui.View(frame=(0, 0, 560, 560), bg_color='white') v.center = root.bounds.center() b = ui.Button(frame=(0, 0, 50, 50)) v.add_subview(b) b.title = 'Shrink' b.action = shrink b2 = ui.Button(title='expand', frame=(root.width, root.height, -100, -100)) b2.hidden = True b2.action = expand root.add_subview(b2) root.present('sheet') root.add_subview(v)
def initData(self): if self.Loaded > 0: self.Show() return self.Loaded = 1 self.Background = ui.Bar() self.Background.SetParent(self) self.Background.SetSize(wndMgr.GetScreenWidth(), wndMgr.GetScreenHeight()) self.Background.SetPosition(0, 0) self.Background.SetColor( grp.GenerateColor(0.0, 0.0, 0.0, 150.0 / 255.0)) self.Background.Show() self.HeadIMGThinBoard = ui.ThinBoard() self.HeadIMGThinBoard.SetParent(self) self.HeadIMGThinBoard.SetPosition((wndMgr.GetScreenWidth() / 2) - 150, (wndMgr.GetScreenHeight() / 2) - 180) self.HeadIMGThinBoard.SetSize(300, 80) self.HeadIMGThinBoard.Show() self.CloseButton = ui.Button() self.CloseButton.SetParent(self) self.CloseButton.SetPosition((wndMgr.GetScreenWidth() / 2) + 104, (wndMgr.GetScreenHeight() / 2) - 200) self.CloseButton.SetText("") self.CloseButton.SetUpVisual( "images_dungeon\src_illumina\close_button_01.tga") self.CloseButton.SetOverVisual( "images_dungeon\src_illumina\close_button_02.tga") self.CloseButton.SetDownVisual( "images_dungeon\src_illumina\close_button_03.tga") self.CloseButton.SetEvent(self.Open) self.CloseButton.Show() self.StoryTextThinBoard = ui.ThinBoard() self.StoryTextThinBoard.SetParent(self) self.StoryTextThinBoard.SetPosition( (wndMgr.GetScreenWidth() / 2) - 150, (wndMgr.GetScreenHeight() / 2) - 95) self.StoryTextThinBoard.SetSize(300, 400) self.StoryTextThinBoard.Show() self.HeadLineCenterImage = ui.ImageBox() self.HeadLineCenterImage.SetParent(self.StoryTextThinBoard) self.HeadLineCenterImage.SetPosition(150 - 104, 18) self.HeadLineCenterImage.LoadImage( "images_dungeon\src_illumina\center.tga") self.HeadLineCenterImage.Show() self.DungeonNameTextLine = ui.TextLine() self.DungeonNameTextLine.SetParent(self.StoryTextThinBoard) self.DungeonNameTextLine.SetPosition(150, 15) self.DungeonNameTextLine.SetHorizontalAlignCenter() self.DungeonNameTextLine.SetText("Dungeon-Name") self.DungeonNameTextLine.Show() i = 0 x = 8 self.Show()
amount = int(mytext) total += amount sender.title = (str(total) + " oz today") def reset_tap(sender): global total total = 0 add_button.title = ("0 oz today") w, h = ui.get_screen_size() x_middle = w / 2 view = ui.View(frame=(0, 0, w, h)) view.name = 'Drink Tracker' view.background_color = 'white' add_button = ui.Button(title='add water', flex='LRTB', font=('<System>', 24)) add_button.frame = (0, 0, w, h / 2) add_button.action = button_tapped add_button.center = (x_middle, h / 2.25) reset_button = ui.Button(title='reset', font=('<System>', 16)) reset_button.center = (x_middle, h / 1.5) reset_button.action = reset_tap view.add_subview(reset_button) view.add_subview(add_button) view.present('sheet')
map_func=lambda sz: ('Helvetica', sz)) else: slide_value(l, 'font', 20, start_value=40, map_func=lambda sz: ('Helvetica', sz)) toggle = not toggle v = ui.View(frame=(0, 0, 400, 400)) l = ui.Label(text='Text to be animated', font=('Helvetica', 20), name='label1', frame=(100, 20, 200, 100)) b1 = ui.Button(title='move', frame=(20, 300, 80, 50), action=button_action) b2 = ui.Button(title='hide', frame=(120, 300, 80, 50), action=button_action) b3 = ui.Button(title='rotate', frame=(220, 300, 80, 50), action=button_action) b4 = ui.Button(title='custom', frame=(320, 300, 80, 50), action=button_action) b5 = ui.Button(title='color', frame=(20, 350, 80, 50), action=button_action) b6 = ui.Button(title='count', frame=(120, 350, 80, 50), action=button_action) b7 = ui.Button(title='fly_out', frame=(220, 350, 80, 50), action=button_action) b8 = ui.Button(title='font_sz', frame=(320, 350, 80, 50), action=button_action) v.add_subview(l) v.add_subview(b1) v.add_subview(b2) v.add_subview(b3) v.add_subview(b4) v.add_subview(b5) v.add_subview(b6) v.add_subview(b7)
def feedback(): panel = ui.LinearLayoutWidget() panel.add(ui.Label('Leaving comments with logs will help me diagnose\npotential problems with game speed and\nunexpected behaviour.')) panel.add(ui.Button('Leave a comment with a log (preferred)', lambda: sync.comment(sync.get_install_time(), True))) panel.add(ui.Button('Leave a comment without a log', lambda: sync.comment(sync.get_install_time(), False))) ui.set(panel)
def view_md(sender): mdviewwin = ui.View() webview = ui.WebView(frame=(0, 0, mdviewwin.width, mdviewwin.height), flex="WH") webview.load_html(markdown.markdown(editor.get_text())) mdviewwin.add_subview(webview) mdviewwin.present('fullscreen') @ui.in_background def email_md(sender): subject = 'subject=' + urllib.quote(editor.get_path().split('/')[-1]) body = 'body=' + urllib.quote(markdown.markdown(editor.get_text())) webbrowser.open('mailto:?' + subject + '&' + body) if __name__ == '__main__': view = ui.View() #Setup the ui elements b_new = ui.Button(frame=(2, 30, 0, 0), title="New") b_new.action = new_md b_view = ui.Button(frame=(2, 60, 0, 0), title="View") b_view.action = view_md b_email = ui.Button(frame=(2, 90, 0, 0), title="Email") b_email.action = email_md #Add subviews to main view and 'present' ui view.add_subview(b_new) view.add_subview(b_view) view.add_subview(b_email) view.present('sidebar')
# coding: utf-8 # https://forum.omz-software.com/topic/2513/getting-the-parent-of-a-dynamically-method-as-a-function/15 # Here is how I add functionality to built-in ui classes these days, using ProxyTypes. from __future__ import print_function import ui from proxy import ObjectWrapper class ButtonWrapper(ObjectWrapper): def __init__(self, obj): ObjectWrapper.__init__(self, obj) def msg(self, leader): print(leader + ': ' + self.name) button = ButtonWrapper(ui.Button(name='Wrapped ui.Button')) button.msg('Calling extra method')
class MyWebView(WKWebView): def on_greeting(self, message): console.alert(message, 'Message passed to Python', 'OK', hide_cancel_button=True) def do_close_ac(sender): v.close() img_btn = ui.Image.named('iow:ios7_close_outline_256') btn = ui.Button(title='') btn.background_image = img_btn btn.action = do_close_ac url = os.path.abspath('index.html') v = MyWebView( swipe_navigation=True, # デバッグ #delegate=MyWebViewDelegate(), #data_detectors=(WKWebView.PHONE_NUMBER, #WKWebView.LINK), flex='WH') v.load_url(url) v.present(title_bar_color=0, hide_title_bar=1)
inset_rect = ui.Rect(rect.width * inset_factor, rect.height * inset_factor) r = ui.Rect(*rect).inset(*inset_rect) for fs in xrange(0, 1000): fw, fh = ui.measure_string(text, max_width=0, font=(font_name, fs), alignment=ui.ALIGN_LEFT, line_break_mode=ui.LB_TRUNCATE_TAIL) if fw > r.width or fh > r.height: fs_size = fs - 1 break return fs_size if __name__ == '__main__': _frame = ui.Rect(0, 0, 320, 480) v = ui.View(frame=_frame) btn = ui.Button(frame=_frame) btn.title = '99' btn.bg_color = 'purple' fs = font_size_for_rect(_frame, '99', _font_name, inset_factor=_inset) print 'Calculated Font Size = ', fs btn.font = (_font_name, fs) v.add_subview(btn) v.present('sheet')
def __make_bC(self): self.__bC = ui.Button() self.__bC.action = self.__bCA self.add_subview(self.__bC)
bar = (chipsize * i, select_height - chipsize, (chipsize * i) + chipsize, select_height) selected_image.paste(c, bar) selected_image.show() saveit = photos.save_image(selected_image) if saveit is True: console.hud_alert('Sampled image has been saved') elif saveit is False: console.hud_alert('Uh oh, not saved') #Add buttons for all the colors to a scroll view: scroll_view = ui.ScrollView(frame=(0, 0, 400, 400)) scroll_view.content_size = (0, len(colors) * 80) for i, c in enumerate(colors): r, g, b = c[1] color = (float(r / 255.0), float(g / 255.0), float(b / 255.0)) swatch = ui.Button(frame=(0, i * 80, 400, 80), background_color=color) swatch.title = str(c[1]) swatch.flex = 'w' swatch.action = tapped scroll_view.add_subview(swatch) scroll_view.name = 'Random Color Picker' save_button = ui.ButtonItem() save_button.title = 'Save' save_button.action = save_action save_button.tint_color = 'red' scroll_view.right_button_items = [save_button] scroll_view.present('sheet')
def __init__(self,content=None,parent=AppWindows.root(),*args,**kwargs): if content: kwargs['frame']=content.bounds.inset(-self.TOOLBAR_HEIGHT,0,0,0) self.corner_radius=5 ui.View.__init__(self,*args,**kwargs) self._pt=None self.actions={} self.w0=self.width self.h0=self.height # setup toolbar H=self.TOOLBAR_HEIGHT toolbar=ui.View(frame=(0,0,self.width,self.TOOLBAR_HEIGHT), bg_color=(.7,.8,.8,.8)) toolbar.flex='w' self.add_subview(toolbar) close=ui.Button(frame=(0,0,H,H)) close.image=ui.Image.named('iob:close_32') close.action=self.remove toolbar.add_subview(close) minimize=ui.Button(frame=(self.width,0,-H,H)) minimize.image=ui.Image.named('iob:chevron_down_32') toolbar.add_subview(minimize) minimize.flex='L' minimize.action=self.toggle zoom=ui.Button(frame=(minimize.x-8,0,-H,H)) zoom.image=ui.Image.named('iob:arrow_expand_32') zoom.flex='L' zoom.action=self.zoom toolbar.add_subview(zoom) self.lbl=ui.Label(frame=(H+8,0,zoom.x-2*8-2*H,H),flex='wr') toolbar.add_subview(self.lbl) #content self.content_view = \ ui.View(frame=(0,H,self.width,self.height-H), flex='wh', bg_color=(.9,.99,.99,.8)) self.content_view.touch_enabled=False self.content_view.content_mode = ui.CONTENT_BOTTOM self.add_subview(self.content_view) self.resize=ui.ImageView(frame=(self.width-H,self.height-H,H,H)) self.resize.image=ui.Image.named('iob:arrow_resize_32') self.resize.transform=ui.Transform.rotation(pi/2.) self.resize.flex='tl' self.add_subview(self.resize) self.resize.send_to_back() self.content_view.send_to_back() self.resizing=False self.x=self.last_offset[0] self.y=self.last_offset[0] self.last_offset[0]+=H self.last_offset[1]+=H if content: self.content_view.add_subview(content) content.flex='wh' self.lbl.text=content.name #add to top window self.parent = parent self.attach() self.g=Gestures(delegate=self) self.g.add_pan(self,self.handle_touch_moved)
def __init__(self, surf, world): self.player_stats_drawn = 0 self.surf = surf self.world = world self.small = pygame.sprite.Group() self.tab = "items" self.created = 0 #BUTTONS INIT self.tabs = [ ui.Button(650, 50, 100, 32, "Player", self.surf), ui.Button(650, 100, 100, 32, "Items", self.surf), ui.Button(650, 200, 100, 32, "Go Back", self.surf) ] self.invbuttons = [ ui.Button(500, 430, 100, 32, "Drop", self.surf), ui.Button(500, 385, 100, 32, "Use", self.surf) ] self.levelbuttons = [ ui.Button(245, 267, 32, 32, "+1", self.surf), ui.Button(245, 312, 32, 32, "+1", self.surf), ui.Button(245, 357, 32, 32, "+1", self.surf), ui.Button(245, 403, 32, 32, "+1", self.surf), ui.Button(245, 448, 32, 32, "+1", self.surf), ui.Button(245, 494, 32, 32, "+1", self.surf), ] self.invx = 0 self.invy = 0 self.drawn = 0
def SetTextFieldPad(tf, pad=None, clearButtonMode=False, undo_redo_pasteBarButtons=True, textfield_did_change=None): if not pad: back_key = (0.7, 0.7, 0.7) pad = [{ 'keys': 'йцукенгшщзх' }, { 'key': '⌫', 'width': 2, 'back': back_key }, { 'key': 'new row' }, { 'keys': 'фывапролджэ' }, { 'key': '⏎', 'width': 1.5, 'back': back_key }, { 'key': 'new row' }, { 'key': '△', 'back': back_key }, { 'keys': 'ячсмитьбюъ' }, { 'key': '△', 'back': back_key, 'width': 2 }, { 'key': 'new row' }, { 'key': '123', 'width': 1.2, 'back': back_key }, { 'key': '', 'back': back_key }, { 'key': '', 'back': back_key }, { 'key': ' ', 'width': 7 }, { 'key': '123', 'width': 2, 'back': back_key }, { 'key': 'dismiss keyboard', 'icon': 'SF=keyboard', 'width': 2.2, 'back': back_key }] multi_modes = [ ('123', '123', 'AЪВ', 'AЪВ'), ('△', '▲', '#+=', '123'), ('йцукенгшщзх', 'ЙЦУКЕНГШЩЗХ', '1234567890—', '1234567890—'), ('фывапролджэ', 'ФЫВАПРОЛДЖЭ', '@#№€´&*()\'"', 'э$£¥±•`^[]{}'), ('ячсмитьбюъ', 'ЯЧСМИТЬБЮЪ', '%_-+=/;:,.', '§|~…≠\<>!?') ] tfo = ObjCInstance( tf).textField() # UITextField is subview of ui.TextField # modes: 0=alpha_lower 1=alpha_upper 2=num 3=spec tf.mode = 0 def key_pressed(sender): if sender.title == 'test': return tfb = sender.TextField tfobjc = ObjCInstance(tfb).textField() cursor = tfobjc.offsetFromPosition_toPosition_( tfobjc.beginningOfDocument(), tfobjc.selectedTextRange().start()) old_mode = tfb.mode if sender.name == '': return elif sender.name == 'delete': if cursor <= (len(tfb.text) - 1): tfb.text = tfb.text[:cursor] + tfb.text[cursor + 1:] elif sender.name == '⌫': if cursor > 0: #if tfb.text != '': tfb.text = tfb.text[:cursor - 1] + tfb.text[cursor:] cursor = cursor - 1 elif sender.name == '⏎': tfb.end_editing() return elif sender.title == '123': tfb.mode = 2 # mode 2=num elif sender.title == '#+=': tfb.mode = 3 # mode 3=spec elif sender.title == 'AЪВ': tfb.mode = 0 # mode 0=alpha_lower elif sender.title == '△': tfb.mode = 1 # 1=alpha_upper elif sender.title == '▲': tfb.mode = 0 # 0=alpha_lower elif sender.name == 'dismiss keyboard': tfb.end_editing() return else: tfb.text = tfb.text[:cursor] + sender.title + tfb.text[cursor:] cursor = cursor + 1 if tfb.mode != old_mode: # update keys titles # tfb.mode_buttons = [(button,'abcd'),(button,('a','b','c','d')) font = 'Menlo' for b, t in tfb.mode_buttons: if isinstance(t, tuple): b.title = t[tfb.mode] else: i = tfb.mode * len(b.title) b.title = t[i:i + len(b.title)] # eventually reset font size because title could be wider # ex: ▲ --> #+= font_size = 32 while True: w = ui.measure_string(b.title, font=(font, font_size))[0] if w < (b.width - 4): break else: font_size -= 1 b.font = (font, font_size) if b.title == '△': b.background_color = back_key elif b.title == '▲': b.background_color = 'white' if textfield_did_change: textfield_did_change(tfb) # set cursor cursor_position = tfobjc.positionFromPosition_offset_( tfobjc.beginningOfDocument(), cursor) tfobjc.selectedTextRange = tfobjc.textRangeFromPosition_toPosition_( cursor_position, cursor_position) # design your keyboard # pad = [{key='functionnality',title='title',icon='icon'},...] # '' => empty key, no action # new row => new row # nul => no key # ⌫ => left delete # delete => right delete # done => discard the keyboard # other => append the character # count the maximum width of rows db = 99999 # we search a minimum dd = 10 row_max_length = 0 row_max_number = 0 row_length = 0 row_number = 0 new_pad = [] rows = [] for pad_elem in pad: if 'keys' in pad_elem: for key in pad_elem['keys']: elem = {'key': key} for k in pad_elem: if k != 'keys': elem[k] = pad_elem[k] new_pad.append(elem) else: new_pad.append(pad_elem) for pad_elem in (new_pad + [{'key': 'new row'}]): if pad_elem['key'] == 'new row': if row_length > row_max_length: row_max_length = row_length if row_number > row_max_number: row_max_number = row_number db = min( (ui.get_screen_size()[0] - (row_number + 1) * dd) / row_length, db) rows.append((row_length, row_number)) row_length = 0 row_number = 0 else: row_number += 1 if 'width' in pad_elem: row_length += float(pad_elem['width']) else: row_length += 1 rows.append((0, 0)) v = ui.View() v.background_color = 'lightgray' y = dd irow = 0 row_length, row_number = rows[irow] x = ui.get_screen_size()[0] - (row_number - 1) * dd - row_length * db - dd mode_buttons = [] for pad_elem in new_pad: if pad_elem['key'] == 'new row': y = y + db + dd irow += 1 row_length, row_number = rows[irow] x = ui.get_screen_size()[0] - (row_number - 1) * dd - row_length * db - dd elif pad_elem['key'] == 'nul': x = x + db + dd else: b = ui.Button() b.name = pad_elem['key'] b.background_color = 'white' # or any other color b.tint_color = 'black' b.corner_radius = 10 b.title = '' if 'icon' in pad_elem: if pad_elem['icon'].startswith('SF='): o = ObjCClass('UIImage').systemImageNamed_( pad_elem['icon'][3:]) with ui.ImageContext(64, 32) as ctx: o.drawAtPoint_(CGPoint(16, 6)) if pad_elem['icon'] == 'SF=keyboard': h = 12 ui.draw_string('˅', rect=(28, 20, h, h), font=('<System-Bold>', h)) b.background_image = ctx.get_image( ).with_rendering_mode(ui.RENDERING_MODE_ORIGINAL) ObjCInstance(b).setContentMode_(2) else: b.image = ui.Image.named( pad_elem['icon']).with_rendering_mode( ui.RENDERING_MODE_ORIGINAL) elif 'title' not in pad_elem: b.title = pad_elem['key'] if 'title' in pad_elem: b.title = pad_elem['title'] if 'width' in pad_elem: dbb = db * pad_elem['width'] else: dbb = db if 'back' in pad_elem: b.background_color = pad_elem['back'] b.frame = (x, y, dbb, db) font = 'Menlo' font_size = 32 while True: w = ui.measure_string(b.title, font=(font, font_size))[0] if w < (b.width - 4): break else: font_size -= 1 b.font = (font, font_size) b.TextField = tf # store tf as key attribute needed when pressed b.action = pad_elem.get('action', key_pressed) v.add_subview(b) if b.title != '': l = len(b.title) for r in multi_modes: if b.title in r: # key is a function like 123/ABC/▲/△ mode_buttons.append((b, r)) break elif l == 1 and b.title in r[0]: # key is one letter/dogot/special i = r[0].index(b.title) c = r[0][i:i + l] + r[1][i:i + l] + r[2][i:i + l] + r[3][i:i + l] mode_buttons.append((b, c)) break x = x + dbb + dd y = y + db + dd tf.mode_buttons = mode_buttons v.width = ui.get_screen_size()[0] v.height = y # view of keyboard retain_global( v ) # see https://forum.omz-software.com/topic/4653/button-action-not-called-when-view-is-added-to-native-view tfo.setInputView_(ObjCInstance(v)) # color of cursor and selected text tfo.tintColor = UIColor.redColor().colorWithAlphaComponent(0.5) # clear button tfo.clearButtonMode = clearButtonMode # comment both lines to keep undo/redo/paste BarButtons above keyboard if not undo_redo_pasteBarButtons: tfo.inputAssistantItem().setLeadingBarButtonGroups(None) tfo.inputAssistantItem().setTrailingBarButtonGroups(None)