smstuebe / stackoverflow-answers

Stackoverflow Answer repository
6 stars 8 forks source link

iOS: if label has been removed, null exception in SetUnderline #1

Open DeerSteak opened 6 years ago

DeerSteak commented 6 years ago

First of all, thanks for this tutorial. I've found multiple effects to be useful in my work.

In the iOS portion of the effect, this section results in a NullReferenceException:

{
                    var range = new NSRange(0, text.Length);

                    if (underlined)
                    {
                        text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                    }
                    else
                    {
                        text.RemoveAttribute(UIStringAttributeKey.UnderlineStyle, range);
                    }
}

I'm not familiar with github (I work in an all-Microsoft environment so I'm really only familiar with TFS) so I don't know how to send a pull request, but I wrapped that whole section in

if (text != null)
{
                    var range = new NSRange(0, text.Length);

                    if (underlined)
                    {
                        text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                    }
                    else
                    {
                        text.RemoveAttribute(UIStringAttributeKey.UnderlineStyle, range);
                    }
}

And that made the issue go away. Since the label has been discarded, there's no reason to go through the un-underlining process.

JungleJ0n commented 6 years ago

I believe the original creator has long abandoned this project.

For readability, instead of wrapping multiple statements in the IF, invert the it and return:

           try
            {
                var label = (UILabel)Control;
                var text = (NSMutableAttributedString)label.AttributedText;

               if (text == null) return;

                var range = new NSRange(0, text.Length);

                if (underlined)
                {
                    text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                }
                else
                {
                    text.RemoveAttribute(UIStringAttributeKey.UnderlineStyle, range);
                }
            }
smstuebe commented 6 years ago

@JungleJ0n + @DeerSteak: Underline is now implemented in Xamarin Forms :) https://github.com/xamarin/Xamarin.Forms/pull/2221 It will be available soonish :)