Forum Archive

Using ObjCClass with a textField

astrozot

Hi,

I need to use some features of the UITextField that are not included in the ui.TextField: specifically, I want to use a text with attributes (attributedText) and set the inputView of an object created with field = objc_util.ObjCInstance(ui.TextField()).

I tried in several ways, but I do not seem able to access the attributedText (or inputView) properties directly. I tried three different techniques:

  • A direct access to the field.attributedText produces no result. I naively thought that there is a mapping between Python and Objective C properties, but this does not seem to be the case.

  • I tried then field.setAttributedText_(...), but in this case objc_util complains with an error.

  • Finally, if I try the more involved setValue_forKey_ method, that crashes Pythonista.

Any help is greatly appreciated!

N.B. I managed to create an object with ObjCClass('UITextField') and then add it to a view with ObjCInstance(view).addSubview_, but I presume there must be a way that uses all the nice infrastructure of a ui.TextField without duplicating the work done already in the ui module.

import ui
from objc_util import *

@on_main_thread
def test():
  field = ui.TextField()    
  fieldc = ObjCInstance(field)

  red = UIColor.redColor()
  mystring = ObjCClass('NSMutableAttributedString').alloc()
  mystring.initWithString_('quick test')
  mystring.setAttributes_range_({'NSColor': red}, NSRange(1,2))
  # The following line produces no result
  fieldc.attributedText = mystring
  # Pythonista complains that setAttributedText: does not exist
  fieldc.setAttributedText_(mystring)
  # The following line makes Pythonista crash
  fieldc.setValue_forKey_(mystring, 'attributedText')
  field.borderStyle = 3 
  view = ui.View()
  view.add_subview(field)
  view.present()

test()
JonB

@astrozot
https://github.com/jsbain/objc_hacks/blob/master/attribtext2.py
is a working example.

Another very robust example, and one that suses the dict approach is in stash/system/screens

astrozot

@JonB
Thank you for your reply, which however seems to apply only to TextView's and not to TextField's: if I use in the working example you provide a TextField I still get the error message I pointed out in my second bullet (and, indeed, the working example uses the second technique I tried).

So the question remains: how can I access the attributedText of a UITextField?

omz

@astrozot The actual UITextField is a subview of ui.TextField that is stored in its textField property. Sounds confusing, I know, so here's the relevant code:

# ...
field = ui.TextField()
fieldc = ObjCInstance(field).textField()
# ...
astrozot

@omz Thank you so much for your reply, that clarifies everything!