Question

I am trying to create a "label" with different styles on different words, kind of like described here. The problem is - as far as I can see - the MonoTouch implementation of UATextLayer does not accept assigning an NSAttributedString to the String property since the String property has the type string.

Is this an error in the implementation or is there another way of doing this?

(Yes, I am aware I can add separate labels - but I would rather not when there is a better solution).

EDIT (in response to the answer from Miguel):

After changing to GetHandler and correcting to "void_objc_msgSend_IntPtr" instead of "void_objc_msgSend_IntPrt" the code in the answer compiles and runs, but it doesn't quite work anyway (I was a bit fast in marking it as the answer). No errors are thrown, but the text doesn't show.

Code:

string _text="Example string";
if(_textLayer==null) {
    _textLayer = new CATextLayer();
    _textLayer.Frame = new RectangleF(50,698,774,50);
    _textLayer.Wrapped=true;
    _textLayer.ForegroundColor=UIColor.White.CGColor;
    _textLayer.BackgroundColor=UIColor.Clear.CGColor;
    Layer.AddSublayer(_textLayer);
}

//_textLayer.String=_text;
CTFont _font=new CTFont("MarkerFelt-Thin",48);
CTStringAttributes _attrs=new CTStringAttributes();
_attrs.Font=_font;
_attrs.ForegroundColor = UIColor.White.CGColor;

var nsa = new NSAttributedString(_text);
Messaging.void_objc_msgSend_IntPtr(
        _textLayer.Handle,
        Selector.GetHandle("string"), 
        nsa.Handle);

If I uncomment the _textLayer.String=_text I see the text (but without attributes of course), so the problem is not with the layer.

Was it helpful?

Solution

For now, you can try:

using MonoTouch.ObjCRuntime;

var caTextLayer = new CATextLayer ();
var nsa = new NSAttributedString ();
[..]
Messaging.void_objc_msgSend_IntPrt (
    caTextLayer.Handle, 
    Selector.sel_registerName ("string"), 
    nsa.Handle);

Alternatively, can you download this preview of the upcoming version:

http://tirania.org/tmp/monotouch.dll

It implements a property AttributedString in CATextLayer that you can set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top