Forum Archive

[Share Code] UIAlertController

blmacbeth

I know Pythonista already has this with the console module, but I think it is a decent look at how to work with other UIViewControllers. This is very raw and needs to be cleaned up… maybe I'll make it into a class. Any way, here is the code


# coding: utf-8
from objc_util import *
import ui

UIAlertController = ObjCClass('UIAlertController')
UIAlertAction     = ObjCClass('UIAlertAction')

def ok_pressed(sender):
    print 'OK pressed'

app = UIApplication.sharedApplication()
win = app.keyWindow()
rvc = win.rootViewController()
## this was all setup for thealert view

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, alert_action_block)
alert.addAction_(default_action)
rvc.presentViewController_animated_completion_(alert, True, None)

Let me know what you think,
B

blmacbeth

Replying so people see this. I found a way to stop the crashing and (fun stuff) found out how to get the custom view controller that is created with each view. This allows you to use the view controller's methods to present oth view controllers!

# coding: utf-8
from objc_util import *
import ctypes
import ui

SUIViewController = ObjCClass('SUIViewController')
UIAlertController = ObjCClass('UIAlertController')
UIAlertAction     = ObjCClass('UIAlertAction')

def ok_pressed(sender):
    print 'OK pressed'

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')

Hope you find this useful,
B