Exemplo n.º 1
0
        public void Set(Uri imgUrl, string time, UIImage actionImage, 
            NSMutableAttributedString header, NSMutableAttributedString body, 
            List<Link> headerLinks, List<Link> bodyLinks, Action<NSUrl> webLinkClicked, bool multilined)
        {
            if (imgUrl == null)
                Image.Image = Images.Avatar;
            else
                Image.SetImage(new NSUrl(imgUrl.AbsoluteUri), Images.Avatar);
            
            Time.Text = time;
            ActionImage.Image = actionImage;

            if (header == null)
                header = new NSMutableAttributedString();
            if (body == null)
                body = new NSMutableAttributedString();

            Header.AttributedText = header;
            Header.Delegate = new LabelDelegate(headerLinks, webLinkClicked);

            Body.AttributedText = body;
            Body.Hidden = body.Length == 0;
            Body.Lines = multilined ? 0 : 4;
            Body.Delegate = new LabelDelegate(bodyLinks, webLinkClicked);

            foreach (var b in headerLinks)
                Header.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range);

            foreach (var b in bodyLinks)
                Body.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range);

            AdjustableConstraint.Constant = Body.Hidden ? 0f : 6f;
        }
Exemplo n.º 2
0
        private static Tuple<NSMutableAttributedString,List<NewsCellView.Link>> CreateAttributedStringFromBlocks(IEnumerable<TextBlock> blocks)
        {
            var attributedString = new NSMutableAttributedString();
            var links = new List<NewsCellView.Link>();

            nint lengthCounter = 0;
            int i = 0;

            foreach (var b in blocks)
            {
                UIColor color = null;
                if (b.Color != null)
                    color = b.Color;
                else
                {
                    if (b.Tapped != null)
                        color = LinkColor;
                }

                var font = b.Font ?? UIFont.PreferredSubheadline;
                color = color ?? Theme.CurrentTheme.MainTextColor;
                var ctFont = new CoreText.CTFont(font.Name, font.PointSize);
                var str = new NSAttributedString(b.Value, new CoreText.CTStringAttributes { ForegroundColor = color.CGColor, Font = ctFont });
                attributedString.Append(str);
                var strLength = str.Length;

                if (b.Tapped != null)
                    links.Add(new NewsCellView.Link { Range = new NSRange(lengthCounter, strLength), Callback = b.Tapped, Id = i++ });

                lengthCounter += strLength;
            }

            return new Tuple<NSMutableAttributedString, List<NewsCellView.Link>>(attributedString, links);
        }
Exemplo n.º 3
0
        private static Tuple<NSMutableAttributedString,List<NewsCellView.Link>> CreateAttributedStringFromBlocks(UIFont font, UIColor primaryColor, IEnumerable<TextBlock> blocks)
        {
            var attributedString = new NSMutableAttributedString();
            var links = new List<NewsCellView.Link>();

            nint lengthCounter = 0;
            int i = 0;

            foreach (var b in blocks)
            {
                UIColor color = null;
                if (b.Tapped != null)
                    color = LinkColor;

                color = color ?? primaryColor; 

                var ctFont = new CoreText.CTFont(font.Name, font.PointSize);
                var str = new NSAttributedString(b.Value, new CoreText.CTStringAttributes() { ForegroundColor = color.CGColor, Font = ctFont });
                attributedString.Append(str);
                var strLength = str.Length;

                if (b.Tapped != null)
                {
                    var weakTapped = new WeakReference<Action>(b.Tapped);
                    links.Add(new NewsCellView.Link { Range = new NSRange(lengthCounter, strLength), Callback = () => weakTapped.Get()?.Invoke(), Id = i++ });
                }

                lengthCounter += strLength;
            }

            return new Tuple<NSMutableAttributedString, List<NewsCellView.Link>>(attributedString, links);
        }
        public static NSAttributedString ToAttributedString(this ITrade trade)
        {
            var currency = trade.CurrencyPair.Replace(trade.DealtCurrency, "");
            var sold = trade.Direction == Direction.BUY ? "Bought" : "Sold";

            var text = new NSMutableAttributedString();
            bool successful = trade.TradeStatus == TradeStatus.Done;

            if (successful)
            {
                text.Append($"{sold} ", _grey);
            }
            else
            {                
                text.Append($"TRADE REJECTED ", _rejected);
            }

            var normal = successful ? _normal : _rejectedNormal;
            var grey = successful ? _grey : _rejectedGrey;
            var small = successful ? _small : _rejectedSmall;
            var smallGrey = successful ? _smallGrey : _rejectedSmallGrey;

            text.Append($"{trade.DealtCurrency} {trade.Notional:n0}", normal);
            text.Append("\n vs ", grey);
            text.Append(currency, normal);
            text.Append("\n at ", grey);
            text.Append(trade.SpotRate.ToString(), normal);
            text.Append("\n", normal);
            text.Append("\nTrade ID: ", smallGrey);
            text.Append(trade.TradeId.ToString(), small);
            return text;
        }
        public static UIButton ConfigureTwoLineButtonWithStates(this UIButton button, string label)
        {
            var split = label.Split ();

            var normalText = new UIStringAttributes {
                Font = UIFont.SystemFontOfSize (14),
                ForegroundColor = CustomColors.Blue

            };
            var selectedText = new UIStringAttributes {
                Font = UIFont.SystemFontOfSize (14),
                ForegroundColor = UIColor.White

            };

            var normalTitle = new NSMutableAttributedString (label.ToUpper ());
            normalTitle.SetAttributes (normalText.Dictionary, new NSRange (0, label.Length));

            var selectedTitle = new NSMutableAttributedString (label.ToUpper ());
            selectedTitle.SetAttributes (selectedText.Dictionary, new NSRange (0, label.Length));

            button.SetAttributedTitle (normalTitle, UIControlState.Normal);
            button.SetAttributedTitle (selectedTitle, UIControlState.Selected);
            button.TitleLabel.Lines = 2;
            button.TitleLabel.TextAlignment = UITextAlignment.Center;

            return button;
        }
Exemplo n.º 6
0
		private NSMutableAttributedString createTalknowAttributed (SpecialistProfileInfos specialistInfo)
		{
			string text1 = TCLocalizabled.getText ("TextMessageConfirmTalknow1");
			string param1 = specialistInfo.Account.Name == null ? "" : specialistInfo.Account.Name;
			string text2 = TCLocalizabled.getText ("TextMessageConfirmTalknow2");
			string param2 = "$" + MUtils.getCost((double)specialistInfo.SpecialistDetail.Specializations [0].CustomerPricing.TalkNow);

			string text3 = TCLocalizabled.getText ("TextMessageConfirmTalknow3");
		
			string param3 = "$" + MUtils.getCost ((double)specialistInfo.SpecialistDetail.Specializations [0].CustomerPricing.Minimum);

			string text4 = String.Format (TCLocalizabled.getText ("TextMessageConfirmTalknow4"), MApplication.getInstance ().typeCard);

			var attributedString = new NSMutableAttributedString (text1 + param1 + text2 + param2 + text3 + param3 + text4);
			UIFont fontMessage = MUtils.getFontWithSize (false, 14.0f);

			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = UIColor.Black

			}.Dictionary, new NSRange (0, text1.Length));
					
			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = TCTheme.getInstance.getThemeColor (Theme.TextColorBooking)

			}.Dictionary, new NSRange (text1.Length, param1.Length));

			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = UIColor.Black

			}.Dictionary, new NSRange ((text1 + param1).Length, text2.Length));
					
			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = TCTheme.getInstance.getThemeColor (Theme.TextColorBooking)

			}.Dictionary, new NSRange ((text1 + param1 + text2).Length, param2.Length));

			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = UIColor.Black, 

			}.Dictionary, new NSRange ((text1 + param1 + text2 + param2).Length, text3.Length));

			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = TCTheme.getInstance.getThemeColor (Theme.TextColorBooking), 

			}.Dictionary, new NSRange ((text1 + param1 + text2 + param2 + text3).Length, param3.Length));

			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = UIColor.Black, 

			}.Dictionary, new NSRange ((text1 + param1 + text2 + param2 + text3 + param3).Length, text4.Length));

			return attributedString;
		}
        public SettingsInstructionView()
        {
            Layer.BorderColor = UIColor.LightGray.CGColor;
            Layer.CornerRadius = 10f;
            Layer.BorderWidth = 1f;
            BackgroundColor = UIColor.LightGray.ColorWithAlpha (.1f);

            Add(topLabel = new UILabel ());

            var firstAttributes = new UIStringAttributes {
                ForegroundColor = UIColor.Blue,
                BackgroundColor = UIColor.Yellow,
                Font = UIFont.FromName("Courier", 18f)
            };

            var secondAttributes = new UIStringAttributes {
                ForegroundColor = UIColor.Red,
                BackgroundColor = UIColor.Gray,
                StrikethroughStyle = NSUnderlineStyle.Single
            };

            var thirdAttributes = new UIStringAttributes {
                ForegroundColor = UIColor.Green,
                BackgroundColor = UIColor.Black
            };

            var prettyString = new NSMutableAttributedString ("UITextField is not pretty!");
            prettyString.SetAttributes (firstAttributes.Dictionary, new NSRange (0, 11));
            prettyString.SetAttributes (secondAttributes.Dictionary, new NSRange (15, 3));
            prettyString.SetAttributes (thirdAttributes.Dictionary, new NSRange (19, 6));

            // assign the styled text
            topLabel.AttributedText = prettyString;
        }
Exemplo n.º 8
0
        public NSAttributedString GetAttributedText()
        {
            string path = null;
            NSError error = new NSError ();

            if (TextStoragePath != null)
                path = NSBundle.MainBundle.PathForResource ("TextFiles/" + TextStoragePath[0], "");
            else
                path = NSBundle.MainBundle.PathForResource ("TextFiles/" + Title, "rtf");

            if (path == null)
                return new NSAttributedString ("");

            if (StrRichFormatting) {
                //  Load the file from disk
                var attributedString = new NSAttributedString (new NSUrl (path, false), null, ref error);

                // Make a copy we can alter
                var attributedTextHolder = new NSMutableAttributedString (attributedString);

                attributedTextHolder.AddAttributes (new UIStringAttributes () { Font = UIFont.PreferredBody },
                    new NSRange (0, attributedTextHolder.Length));
                AttributedText = (NSAttributedString)attributedTextHolder.Copy ();
            } else {
                string newFlatText = new NSAttributedString (new NSUrl (path, false), null, ref error).Value;
                AttributedText = new NSAttributedString (newFlatText, font: UIFont.PreferredBody);
            }

            return AttributedText;
        }
Exemplo n.º 9
0
		private NSMutableAttributedString createASAPAttributed (SpecialistProfileInfos specialistInfo)
		{
			string text1 = TCLocalizabled.getText ("TextMessageConfirmSoonest1");
			string param1 = specialistInfo.Account.Name == null ? "" : specialistInfo.Account.Name;
			string text2 = TCLocalizabled.getText ("TextMessageConfirmSoonest2");
			string param2 = "$" + MUtils.getCost((double)specialistInfo.SpecialistDetail.Specializations [0].CustomerPricing.Minimum);
			string text3 = TCLocalizabled.getText ("TextMessageConfirmSoonest3");
		
			var attributedString = new NSMutableAttributedString (text1 + param1 + text2 + param2 + text3);
			UIFont fontMessage = MUtils.getFontWithSize (false, 14.0f);

			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = UIColor.Black

			}.Dictionary, new NSRange (0, text1.Length));

			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = TCTheme.getInstance.getThemeColor (Theme.TextColorBooking)

			}.Dictionary, new NSRange (text1.Length, param1.Length));
					
			attributedString.SetAttributes (new UIStringAttributes {
				Font = fontMessage,
				ForegroundColor = TCTheme.getInstance.getThemeColor (Theme.TextColorBooking)

			}.Dictionary, new NSRange ((text1 + param1 + text2).Length, param2.Length));
					
			return attributedString;
		}
Exemplo n.º 10
0
        private void UpdateText ()
        {
            var durationShown = digitsEntered > 0 ? duration : hintDuration;
            var durationText = String.Concat (" ", durationShown.ToString (), " ");

            var durationAttributed = new NSMutableAttributedString (durationText);
            if (digitsEntered > 0) {
                // Divider
                var sepIdx = durationText.IndexOf (":", StringComparison.Ordinal);
                if (sepIdx >= 0) {
                    durationAttributed.AddAttributes (
                    new UIStringAttributes () { ForegroundColor = HighlightedTextColor },
                    new NSRange (sepIdx, 1)
                    );
                }
                // Color entered minutes
                var minutesLength = Math.Min (digitsEntered, 2);
                durationAttributed.AddAttributes (
                new UIStringAttributes () { ForegroundColor = HighlightedTextColor },
                new NSRange (durationText.Length - 1 - minutesLength, minutesLength)
                );
                // Color entered hours
                if (digitsEntered > 2) {
                    var hoursLength = digitsEntered - 2;
                    durationAttributed.AddAttributes (
                    new UIStringAttributes () { ForegroundColor = HighlightedTextColor },
                    new NSRange (1 + 2 - hoursLength, hoursLength)
                    );
                }
            }
            AttributedText = durationAttributed;
        }
Exemplo n.º 11
0
        public void FormatCode(NSMutableAttributedString fs)
        {
            var s = fs.Value;
            var n = s.Length;
            var p = 0;

            fs.SetAttributes (baseAttrs, new NSRange (0, n));

            if (n == 0)
                return;

            Func<char, bool> isDigit = ch => {
                var l = char.ToLowerInvariant (ch);
                return l == '.' || l == 'a' || l=='b'||l=='c'||l=='d'||l=='e'||l=='f'||l=='x'||char.IsDigit (ch);
            };

            while (p < n) {
                var wsp = p;
                while (p < n && char.IsWhiteSpace (s [p])) {
                    p++;
                }
                if (p != wsp) {
                    fs.AddAttributes (wsAttrs, new NSRange (wsp, p - wsp));
                }
                if (p >= n)
                    break;

                var ch = s [p];
                if (ch == '_' || char.IsLetter (ch)) {

                    var sp = p;
                    while (p < n && (s[p] == '_' || char.IsLetterOrDigit (s[p]))) {
                        p++;
                    }
                    var len = p - sp;
                    var ss = s.Substring (sp, len);
                    if (keywords.Contains (ss)) {
                        fs.AddAttributes (kwdAttrs, new NSRange (sp, len));
                    } else if (valwords.Contains (ss)) {
                        fs.AddAttributes (valAttrs, new NSRange (sp, len));
                    } else if (gwords.Contains (ss)) {
                        fs.AddAttributes (gAttrs, new NSRange (sp, len));
                    } else {
                        fs.AddAttributes (identAttrs, new NSRange (sp, len));
                    }

                } else if (char.IsDigit (ch)) {
                    var sp = p;
                    while (p < n && isDigit (s[p])) {
                        p++;
                    }
                    fs.AddAttributes (valAttrs, new NSRange (sp, p - sp));

                } else {
                    p++;
                }
            }
        }
        public static NSAttributedString ToAttributedStringLine1(this ITrade trade)
        {
            var sold = trade.Direction == Direction.BUY ? "Bought" : "Sold";
            var text = new NSMutableAttributedString();

            text.Append($"{sold} ", _grey);
            text.Append($"{trade.DealtCurrency} {trade.Notional:n0}\n", _normal);
            return text;
        }
        /// <summary>
        /// Updates the UI.
        /// </summary>
        /// <param name="view">
        /// The view.
        /// </param>
        /// <param name="control">
        /// The control.
        /// </param>
        private static void UpdateUi(ExtendedLabel view, UILabel control)
        {
            if (view.FontSize > 0)
            {
                control.Font = UIFont.FromName(control.Font.Name,(float)view.FontSize);
            }

            if (!string.IsNullOrEmpty(view.FontName))
            {
                string fontName = view.FontName;
                //if extension given then remove it for iOS
                if (fontName.LastIndexOf(".", System.StringComparison.Ordinal) == fontName.Length - 4)
                {
                    fontName = fontName.Substring(0, fontName.Length - 4);
                }

                var font = UIFont.FromName(
                    fontName, control.Font.PointSize);

                if (font != null)
                {
                    control.Font = font;
                }
            }

            //======= This is for backward compatability with obsolete attrbute 'FontNameIOS' ========
            if (!string.IsNullOrEmpty(view.FontNameIOS))
            {
                var font = UIFont.FromName(
                    view.FontNameIOS,
                   (view.FontSize > 0) ? (float)view.FontSize : 12.0f);

                if (font != null)
                {
                    control.Font = font;
                }
            }
            //====== End of obsolete section ==========================================================

            var attrString = new NSMutableAttributedString(control.Text);

            if (view.IsUnderline)
            {
                //control.AttributedText = new NSAttributedString(
                //    control.Text,
                //    underlineStyle: NSUnderlineStyle.Single);

                attrString.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attrString.Length));
            }

            if (view.IsStrikeThrough)
            {
                attrString.AddAttribute(UIStringAttributeKey.StrikethroughStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attrString.Length));
            }

            control.AttributedText = attrString;
        }
        private static void SetText(Labs.Controls.IconButton iconButton, UIButton targetButton)
        {
            var renderedIcon = iconButton.Icon;

            // if no IconFontName is provided on the IconButton, default to FontAwesome
            var iconFontName = string.IsNullOrEmpty(iconButton.IconFontName)
                ? "fontawesome"
                : iconButton.IconFontName;

            var iconSize = iconButton.IconSize == default(float)
                ? 17f
                : iconButton.IconSize;

            var faFont = UIFont.FromName(iconFontName, iconSize);

            // set the icon to either be on the left or right of the button's text
            string combinedText = iconButton.Orientation == ImageOrientation.ImageToLeft 
                ? string.Format("{0}  {1}", renderedIcon, iconButton.Text) 
                : string.Format("{0}  {1}", iconButton.Text, renderedIcon);


            // string attributes for the icon
            var iconAttributes = new UIStringAttributes
            {
                ForegroundColor = iconButton.IconColor.ToUIColor(),
                BackgroundColor = targetButton.BackgroundColor,
                Font = faFont,
                TextAttachment = new NSTextAttachment()
            };

            // string attributes for the button's text. 
            // TODO: Calculate an appropriate BaselineOffset for the main button text in order to center it vertically relative to the icon
            var btnAttributes = new UIStringAttributes
            {
                BackgroundColor = iconButton.BackgroundColor.ToUIColor(),
                ForegroundColor = iconButton.TextColor.ToUIColor(),
                Font = GetButtonFont(iconButton,targetButton)
            };

            // Give the overall string the attributes of the button's text
            var prettyString = new NSMutableAttributedString(combinedText,btnAttributes);

            // Set the font for only the icon (1 char)
            prettyString.SetAttributes(iconAttributes.Dictionary,
                iconButton.Orientation == ImageOrientation.ImageToLeft
                    ? new NSRange(0, 1)
                    : new NSRange(prettyString.Length - 1, 1));


            // set the final formatted string as the button's text
            targetButton.SetAttributedTitle(prettyString, UIControlState.Normal);

            // center the button's contents
            targetButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;
            targetButton.TitleLabel.TextAlignment = UITextAlignment.Center;
        }
Exemplo n.º 15
0
 private NSAttributedString IterateChildNodes(XElement element, CTStringAttributes baseAttribs)
 {
     NSMutableAttributedString mutString = new NSMutableAttributedString ("");
     foreach (var child in element.Nodes()) {
         NSAttributedString formatted = NodeToAttributedString (child, baseAttribs);
         if (formatted != null)
             mutString.Append (formatted);
     }
     return mutString;
 }
Exemplo n.º 16
0
 public NSAttributedString AttributedMailText(string text)
 {
     Random r = new Random ();
     string randomString = loremIpsum.GenerateString (10 + r.Next (0, 16));
     string str = String.Format ("{0}\n{1}", text, randomString);
     NSMutableAttributedString attrStr = new NSMutableAttributedString (str, new NSDictionary ());
     NSRange range = new NSRange (str.IndexOf ("\n"), "\n".Length);
     attrStr.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Gray, new NSRange(range.Location, str.Length - range.Location));
     return attrStr;
 }
        public static NSAttributedString ToAttributedStringLine2(this ITrade trade)
        {
            var currency = trade.CurrencyPair.Replace(trade.DealtCurrency, ""); // Hack
            var text = new NSMutableAttributedString();

            text.Append("vs ", _grey);
            text.Append(currency, _normal);
            text.Append(" at ", _grey);
            text.Append(trade.SpotRate.ToString(), _normal);
            return text;
        }
Exemplo n.º 18
0
        public static NSAttributedString ToAttributedString(this FormattedPrice price)
        {
            var minorAttributes = new UIStringAttributes { ForegroundColor = UIColor.FromRGB(.7f, .7f, .7f), Font = UIFont.SystemFontOfSize(16), BaselineOffset = 1.5f };
            var majorAttributes = new UIStringAttributes { Font = UIFont.SystemFontOfSize(23) };

            var str = new NSMutableAttributedString(price.BigFigures, minorAttributes);
            str.Append(new NSAttributedString(price.Pips, majorAttributes));
            str.Append(new NSAttributedString(price.TenthOfPip, minorAttributes));

            return str;
        }
        public override void setData()
        {
            lblTitle.Text = "Beschrijving";

            //shows button depending on action
            add = _appController.ShowAdd;
            imgAction.Image = add ? UIImage.FromBundle ("SharedAssets/add_white") : UIImage.FromBundle ("SharedAssets/delete_white");

            if (hidden) {
                lblNumber.Text = "";
                lblHead.Text = "...";
                lblBody.Text = _appController.CurrentTotem.body.Replace (_appController.CurrentTotem.title, "...");
            } else {

                //styling for title (totem name)
                var paragraphStyleTitle = new NSMutableParagraphStyle ();
                paragraphStyleTitle.LineSpacing = 15;

                //styling for synonyms
                var paragraphStyleSyn = new NSMutableParagraphStyle ();
                paragraphStyleSyn.LineSpacing = 20;

                var titleAttributes = new UIStringAttributes {
                    Font = UIFont.FromName ("VerveineW01-Regular", 35f),
                    ParagraphStyle = paragraphStyleTitle
                };

                var synonymsAttributes = new UIStringAttributes {
                    Font = UIFont.FromName ("DIN-LightItalic", 17f),
                    ParagraphStyle = paragraphStyleSyn
                };

                var content = _appController.CurrentTotem.title;
                if (_appController.CurrentTotem.synonyms != null)
                    content += " - " + _appController.CurrentTotem.synonyms;

                //whitespace for UI purposes
                content += "\n";

                //applying attributes
                var title_synonyms = new NSMutableAttributedString (content);
                title_synonyms.SetAttributes (titleAttributes.Dictionary, new NSRange (0, _appController.CurrentTotem.title.Length));
                title_synonyms.SetAttributes (synonymsAttributes.Dictionary, new NSRange (_appController.CurrentTotem.title.Length, (title_synonyms.Length - _appController.CurrentTotem.title.Length)));

                lblNumber.Text = _appController.CurrentTotem.number + ". ";
                lblHead.AttributedText = title_synonyms;

                lblBody.Text = _appController.CurrentTotem.body;
            }

            imgLine.Image = UIImage.FromBundle ("SharedAssets/Lijn_bold");
            imgReturn.Image = UIImage.FromBundle ("SharedAssets/arrow_back_white");
            imgHidden.Image = hidden ? UIImage.FromBundle ("SharedAssets/visibility_white") : UIImage.FromBundle ("SharedAssets/visibility_off_white");
        }
Exemplo n.º 20
0
		public override void ViewDidLayoutSubviews ()
		{
			base.ViewDidLayoutSubviews ();

			var paragraphStyle = new NSMutableParagraphStyle { HyphenationFactor = 1 };
			var attributedString = new NSMutableAttributedString(
				HomeViewModel?.FirstAppointment?.Description ?? string.Empty, 
				paragraphStyle: paragraphStyle);

			meetingDescriptionLabel.AttributedText = attributedString;
			meetingDescriptionLabel.SizeToFit ();
		}
Exemplo n.º 21
0
        public static void SetLineSpacing(this UILabel label, float lineSpacing, UITextAlignment alignment)
        {
            var text           = label.Text ?? "";
            var attributedText = new NSMutableAttributedString(text);
            var range          = new NSRange(0, text.Length);

            var paragraphStyle = new NSMutableParagraphStyle();

            paragraphStyle.LineSpacing = lineSpacing;
            paragraphStyle.Alignment   = alignment;

            attributedText.AddAttribute(UIStringAttributeKey.ParagraphStyle, paragraphStyle, range);

            label.AttributedText = attributedText;
        }
Exemplo n.º 22
0
        /// <summary>
        /// Adds Accessibility label on the label using the raw text containing html
        /// </summary>
        /// <param name="label"></param>
        /// <param name="rawText"></param>
        public static void InitLabelAccessibilityTextWithHTMLFormat(UILabel label, string rawText)
        {
            //Defining attibutes inorder to format the embedded link
            NSAttributedStringDocumentAttributes documentAttributes = new NSAttributedStringDocumentAttributes {
                DocumentType = NSDocumentType.HTML
            };

            documentAttributes.StringEncoding = NSStringEncoding.UTF8;
            NSError            error            = null;
            NSAttributedString attributedString = new NSAttributedString(NSData.FromString(rawText, NSStringEncoding.UTF8), documentAttributes, ref error);

            NSMutableAttributedString text = new NSMutableAttributedString(attributedString);

            label.AccessibilityAttributedLabel = text;
        }
Exemplo n.º 23
0
        private void MarkSpellingForCursorRange()
        {
            var range = new SpaceSeparatedRange(_content.Text, (int)CursorPosition - 50, 100);

            var result = new NSMutableAttributedString(_content.AttributedText);

            result.RemoveAttribute(UIStringAttributeKey.UnderlineStyle, new NSRange(range.StartIndex, range.Length));

            foreach (var misspelledWord in new MisspelledWordsSequence(new UITextChecker(), _content.Text, range))
            {
                result.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), misspelledWord);
            }

            _content.AttributedText = result;
        }
Exemplo n.º 24
0
        public static int resizeUILabelHeight(string text, UIFont font, nfloat width)
        {
            var nsText = new NSMutableAttributedString(text);

            nsText.AddAttribute(UIStringAttributeKey.Font, font, new NSRange(0, nsText.Length));

            var ctxt         = new NSStringDrawingContext();
            var expectedSize = nsText.GetBoundingRect(new CGSize(width, float.MaxValue),
                                                      NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading,
                                                      ctxt).Size;

            int expectedHeight = (int)Math.Round(expectedSize.Height);

            return(expectedHeight);
        }
Exemplo n.º 25
0
        public void DrawText(string text, Rect frame, Font font, TextAlignment alignment = TextAlignment.Left, Pen pen = null, Brush brush = null)
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            if (font == null)
            {
                throw new ArgumentNullException("font");
            }

            SetBrush(brush);

            using (var atext = new NSMutableAttributedString(text)) {
                atext.AddAttributes(new CTStringAttributes {
                    ForegroundColorFromContext = true,
                    StrokeColor = pen != null ? pen.Color.GetCGColor() : null,
                    Font        = font.GetCTFont(),
                }.Dictionary, new NSRange(0, text.Length));

                using (var l = new CTLine(atext)) {
                    nfloat asc, desc, lead;
                    var    len = l.GetTypographicBounds(out asc, out desc, out lead);
                    var    pt  = frame.TopLeft;

                    switch (alignment)
                    {
                    case TextAlignment.Left:
                        pt.X = frame.X;
                        break;

                    case TextAlignment.Center:
                        pt.X = frame.X + (frame.Width - len) / 2;
                        break;

                    case TextAlignment.Right:
                        pt.X = frame.Right - len;
                        break;
                    }

                    context.SaveState();
                    context.TranslateCTM((nfloat)(pt.X), (nfloat)(pt.Y));
                    context.TextPosition = CGPoint.Empty;
                    l.Draw(context);
                    context.RestoreState();
                }
            }
        }
        private NSAttributedString buildString(string project, string task, string client, UIColor color)
        {
            var builder   = new StringBuilder();
            var hasClient = !string.IsNullOrEmpty(client);

            if (!string.IsNullOrEmpty(project))
            {
                builder.Append($" {project}");
            }

            if (!string.IsNullOrEmpty(task))
            {
                builder.Append($": {task}");
            }

            if (hasClient)
            {
                builder.Append($" {client}");
            }

            var text = builder.ToString();

            var result      = new NSMutableAttributedString(text);
            var clientIndex = text.Length - (client?.Length ?? 0);

            if (shouldColorProject)
            {
                var projectNameRange      = new NSRange(0, clientIndex);
                var projectNameAttributes = new UIStringAttributes {
                    ForegroundColor = color
                };
                result.AddAttributes(projectNameAttributes, projectNameRange);
            }

            if (!hasClient)
            {
                return(result);
            }

            var clientNameRange      = new NSRange(clientIndex, client.Length);
            var clientNameAttributes = new UIStringAttributes {
                ForegroundColor = clientColor
            };

            result.AddAttributes(clientNameAttributes, clientNameRange);

            return(result);
        }
Exemplo n.º 27
0
        public static CallMeBackView Create()
        {
            var CallMeBackViewArr = NSBundle.MainBundle.LoadNib("CallMeBackView", null, null);
            var View = Runtime.GetNSObject <CallMeBackView>(CallMeBackViewArr.ValueAt(0));

            /* Set text outlets */

            var LanguageBundle = RetrieveLanguageBundle(LanguageHelper.Language);

            View.HelpQuestion.Text = LanguageBundle.LocalizedString("Help?", null);

            View.PhoneLabel.Text = LanguageBundle.LocalizedString("Phone", null);

            var PhoneImage = new UIImage("img/phone-input.png");

            View.PhoneInput.LeftView     = new UIImageView(PhoneImage);
            View.PhoneInput.LeftViewMode = UITextFieldViewMode.Always;

            var Attributes = new UIStringAttributes();

            Attributes.UnderlineStyle  = NSUnderlineStyle.Single;
            Attributes.ForegroundColor = Colors.DarkPurple;

            var AcceptLegalLocalized = LanguageBundle.LocalizedString("Accept-legal", null);
            var MutableString        = new NSMutableAttributedString(AcceptLegalLocalized);
            var Range = RangeLastTwoWords(AcceptLegalLocalized);

            MutableString.AddAttributes(Attributes, Range);
            View.LegalLabel.AttributedText = MutableString;

            View.CallMeNowButton.SetTitle(LanguageBundle.LocalizedString("Call-me-now", null), UIControlState.Normal);
            View.OrLabel.Text = LanguageBundle.LocalizedString("Or", null);
            View.ICallButton.SetTitle(LanguageBundle.LocalizedString("I-call", null), UIControlState.Normal);

            /* Add gesture recognizer to legal conditions link */

            Action LegalTouchPopOver = () =>
            {
                ShowLegalConditions(View);
            };

            var TapGesture = new UITapGestureRecognizer(LegalTouchPopOver);

            View.LegalLabel.UserInteractionEnabled = true;
            View.LegalLabel.AddGestureRecognizer(TapGesture);

            return(View);
        }
		private void ConfigureTextView()
		{
			TextView.Font = UIFont.FromDescriptor (UIFontDescriptor.PreferredBody, 0);

			TextView.TextColor = UIColor.Black;
			TextView.BackgroundColor = UIColor.White;
			TextView.ScrollEnabled = true;

			// Let's modify some of the attributes of the attributed string.
			// You can modify these attributes yourself to get a better feel for what they do.
			// Note that the initial text is visible in the storyboard.
			var attributedText = new NSMutableAttributedString (TextView.AttributedText);

			// Use NSString so the result of rangeOfString is an NSRange, not Range<String.Index>.
			NSString text = (NSString)TextView.Text;

			// Find the range of each element to modify.
			var boldRange = CalcRangeFor (text, "bold".Localize ());
			var highlightedRange = CalcRangeFor (text, "highlighted".Localize ());
			var underlinedRange = CalcRangeFor (text, "underlined".Localize ());
			var tintedRange = CalcRangeFor (text, "tinted".Localize ());

			// Add bold. Take the current font descriptor and create a new font descriptor with an additional bold trait.
			var boldFontDescriptor = TextView.Font.FontDescriptor.CreateWithTraits (UIFontDescriptorSymbolicTraits.Bold);
			var boldFont = UIFont.FromDescriptor (boldFontDescriptor, 0);
			attributedText.AddAttribute (UIStringAttributeKey.Font, value: boldFont, range: boldRange);

			// Add highlight.
			attributedText.AddAttribute (UIStringAttributeKey.BackgroundColor, value: ApplicationColors.Green, range: highlightedRange);

			// Add underline.
			attributedText.AddAttribute (UIStringAttributeKey.UnderlineStyle, value: NSNumber.FromInt32 ((int)NSUnderlineStyle.Single), range: underlinedRange);

			// Add tint.
			attributedText.AddAttribute (UIStringAttributeKey.ForegroundColor, value: ApplicationColors.Blue, range: tintedRange);

			// Add image attachment.
			var img = UIImage.FromBundle ("text_view_attachment");
			var textAttachment = new NSTextAttachment {
				Image = img,
				Bounds = new CGRect(PointF.Empty, img.Size),
			};

			var textAttachmentString = NSAttributedString.CreateFrom (textAttachment);
			attributedText.Append (textAttachmentString);

			TextView.AttributedText = attributedText;
		}
        private void SetAgreementDecoration()
        {
            var tsAttribute = new UIStringAttributes
            {
                Link            = new NSUrl(Pp),
                Font            = Constants.Regular12,
                ForegroundColor = Constants.R15G24B30,
            };

            var ppAttribute = new UIStringAttributes
            {
                Link            = new NSUrl(Tos),
                Font            = Constants.Regular12,
                ForegroundColor = Constants.R15G24B30,
            };

            var noLinkAttribute = new UIStringAttributes
            {
                Font            = Constants.Regular12,
                ForegroundColor = Constants.R151G155B158,
            };

            var attributedLabel = new TTTAttributedLabel();

            attributedLabel.EnabledTextCheckingTypes = NSTextCheckingType.Link;
            attributedLabel.Lines = 2;

            var prop = new NSDictionary();

            attributedLabel.LinkAttributes       = prop;
            attributedLabel.ActiveLinkAttributes = prop;

            attributedLabel.Delegate = new TTTAttributedLabelCustomDelegate();
            agreementView.AddSubview(attributedLabel);

            var at = new NSMutableAttributedString();

            at.Append(new NSAttributedString("I agree with ", noLinkAttribute));
            at.Append(new NSAttributedString("Terms of Service", tsAttribute));
            at.Append(new NSAttributedString(" & ", noLinkAttribute));
            at.Append(new NSAttributedString("Privacy Policy", ppAttribute));

            attributedLabel.SetText(at);
            attributedLabel.AutoAlignAxis(axis: ALAxis.Horizontal, otherView: termsSwitcher);
            attributedLabel.AutoPinEdgeToSuperviewEdge(ALEdge.Left, 15f);
            termsSwitcher.AutoPinEdge(ALEdge.Left, ALEdge.Right, attributedLabel, 5f);
            termsSwitcher.Layer.CornerRadius = 16;
        }
Exemplo n.º 30
0
        static NSAttributedString ResetFontSize(NSMutableAttributedString attrString)
        {
            defaultFont = UIFont.SystemFontOfSize(defaultSize);

            attrString.EnumerateAttribute(UIStringAttributeKey.Font, new NSRange(0, attrString.Length), NSAttributedStringEnumeration.None, (NSObject value, NSRange range, ref bool stop) =>
            {
                if (value != null)
                {
                    var oldFont       = (UIFont)value;
                    var oldDescriptor = oldFont.FontDescriptor;

                    var newDescriptor = defaultFont.FontDescriptor;

                    bool hasBoldFlag   = false;
                    bool hasItalicFlag = false;

                    if (oldDescriptor.SymbolicTraits.HasFlag(UIFontDescriptorSymbolicTraits.Bold))
                    {
                        hasBoldFlag = true;
                    }
                    if (oldDescriptor.SymbolicTraits.HasFlag(UIFontDescriptorSymbolicTraits.Italic))
                    {
                        hasItalicFlag = true;
                    }

                    if (hasBoldFlag && hasItalicFlag)
                    {
                        uint traitsInt = (uint)UIFontDescriptorSymbolicTraits.Bold + (uint)UIFontDescriptorSymbolicTraits.Italic;
                        newDescriptor  = newDescriptor.CreateWithTraits((UIFontDescriptorSymbolicTraits)traitsInt);
                    }
                    else if (hasBoldFlag)
                    {
                        newDescriptor = newDescriptor.CreateWithTraits(UIFontDescriptorSymbolicTraits.Bold);
                    }
                    else if (hasItalicFlag)
                    {
                        newDescriptor = newDescriptor.CreateWithTraits(UIFontDescriptorSymbolicTraits.Italic);
                    }

                    var newFont = UIFont.FromDescriptor(newDescriptor, defaultSize);

                    attrString.RemoveAttribute(UIStringAttributeKey.Font, range);
                    attrString.AddAttribute(UIStringAttributeKey.Font, newFont, range);
                }
            });

            return(attrString);
        }
        private void SetKerning()
        {
            var    element = Element as KerningLabel;
            string text    = Element.Text;

            if (string.IsNullOrEmpty(text))
            {
                Control.Text = string.Empty;
            }
            else
            {
                var attributedString = new NSMutableAttributedString(text);
                attributedString.AddAttribute(_kerningAttribureName, NSObject.FromObject(element.Kerning), new NSRange(0, text.Length - 1));
                Control.AttributedText = attributedString;
            }
        }
        protected override void OnAttached()
        {
            //(Control as UILabel);
            var paragraphStyle = new NSMutableParagraphStyle()
            {
                LineSpacing = 15
            };

            var strin = new NSMutableAttributedString((Element as Label).Text);
            var style = UIStringAttributeKey.ParagraphStyle;
            var range = new NSRange(0, strin.Length);

            strin.AddAttribute(style, paragraphStyle, range);

            (Control as UILabel).AttributedText = strin;
        }
Exemplo n.º 33
0
 public void Runs()
 {
     using (var mas = new NSMutableAttributedString("Bonjour"))
         using (var rd = new CTRunDelegate(new MyOps())) {
             var sa = new CTStringAttributes()
             {
                 RunDelegate = rd,
             };
             mas.SetAttributes(sa, new NSRange(3, 3));
             using (var fs = new CTFramesetter(mas)) {
                 Assert.True(MyOps.Ascent, "Ascent called");
                 Assert.True(MyOps.Descent, "Descent called");
                 Assert.True(MyOps.Width, "Width called");
             }
         }
 }
Exemplo n.º 34
0
        public static NSAttributedString ToAttributedString(this FormattedPrice price)
        {
            var minorAttributes = new UIStringAttributes {
                ForegroundColor = UIColor.FromRGB(.7f, .7f, .7f), Font = UIFont.SystemFontOfSize(16), BaselineOffset = 1.5f
            };
            var majorAttributes = new UIStringAttributes {
                Font = UIFont.SystemFontOfSize(23)
            };

            var str = new NSMutableAttributedString(price.BigFigures, minorAttributes);

            str.Append(new NSAttributedString(price.Pips, majorAttributes));
            str.Append(new NSAttributedString(price.TenthOfPip, minorAttributes));

            return(str);
        }
Exemplo n.º 35
0
        public NewsFeedElement(string imageUrl, DateTimeOffset time, IEnumerable<TextBlock> headerBlocks, IEnumerable<TextBlock> bodyBlocks, UIImage littleImage, Action tapped)
            : base(null)
        {
            Uri.TryCreate(imageUrl, UriKind.Absolute, out _imageUri);
            _time = time.Humanize();
            _actionImage = littleImage;
            _tapped = tapped;

            var header = CreateAttributedStringFromBlocks(headerBlocks);
            _attributedHeader = header.Item1;
            _headerLinks = header.Item2;

            var body = CreateAttributedStringFromBlocks(bodyBlocks);
            _attributedBody = body.Item1;
            _bodyLinks = body.Item2;
        }
Exemplo n.º 36
0
        public NewsFeedElement(string imageUrl, DateTimeOffset time, IEnumerable<TextBlock> headerBlocks, IEnumerable<TextBlock> bodyBlocks, UIImage littleImage, Action tapped, bool multilined)
        {
            Uri.TryCreate(imageUrl, UriKind.Absolute, out _imageUri);
            _time = time.Humanize();
            _actionImage = littleImage;
            _tapped = tapped;
            _multilined = multilined;

            var header = CreateAttributedStringFromBlocks(UIFont.PreferredBody, Theme.CurrentTheme.MainTextColor, headerBlocks);
            _attributedHeader = header.Item1;
            _headerLinks = header.Item2;

            var body = CreateAttributedStringFromBlocks(UIFont.PreferredSubheadline, Theme.CurrentTheme.MainSubtitleColor, bodyBlocks);
            _attributedBody = body.Item1;
            _bodyLinks = body.Item2;
        }
Exemplo n.º 37
0
        private static NSAttributedString endingWithIcon(string text, NSMutableAttributedString icon)
        {
            var range      = new NSRange(0, 1);
            var attributes = new UIStringAttributes {
                ForegroundColor = UIColor.White
            };

            icon.AddAttributes(attributes, range);

            var result = new NSMutableAttributedString(text);

            result.Append(new NSAttributedString(" ")); // separate the text from the icon
            result.Append(icon);

            return(result);
        }
Exemplo n.º 38
0
        private void FixFontAtLocation(int location, NSMutableAttributedString text, string fontFamily,
                                       FontAttributes fontAttributes)
        {
            if (fontFamily == null)
            {
                return;
            }

            NSRange range;
            var     font    = ( UIFont )text.GetAttribute(UIStringAttributeKey.Font, location, out range);
            var     newName = GetFontName(fontFamily, fontAttributes);

            font = UIFont.FromName(newName, font.PointSize);
            text.RemoveAttribute(UIStringAttributeKey.Font, range);
            text.AddAttribute(UIStringAttributeKey.Font, font, range);
        }
        private static NSMutableAttributedString tryAddColorToDot(NSMutableAttributedString dotString, UIColor color)
        {
            if (color == null)
            {
                return(dotString);
            }

            var range      = new NSRange(0, 1);
            var attributes = new UIStringAttributes {
                ForegroundColor = color
            };

            dotString.AddAttributes(attributes, range);

            return(dotString);
        }
Exemplo n.º 40
0
        private void SetupStatusDisplayTextField()
        {
            NSTextAttachment attachment = new NSTextAttachment
            {
                Image  = NSImage.ImageNamed(NSImageName.ApplicationIcon),
                Bounds = CoreGraphics.CGRect.FromLTRB(0, -4, 14, 10),
            };
            NSAttributedString imageAttributedString = NSAttributedString.FromAttachment(attachment);

            NSMutableAttributedString statusDisplayAttributedString = new NSMutableAttributedString();

            statusDisplayAttributedString.Append(imageAttributedString);
            statusDisplayAttributedString.Append(new NSAttributedString("  Apple Cider 2020 for Mac"));

            StatusDisplayTextField.AttributedStringValue = statusDisplayAttributedString;
        }
Exemplo n.º 41
0
        internal static void AddKerningAdjustment(NSMutableAttributedString mutableAttributedString, string text, double characterSpacing)
        {
            if (!string.IsNullOrEmpty(text))
            {
                if (characterSpacing == 0 && !mutableAttributedString.HasCharacterAdjustment())
                {
                    return;
                }

                mutableAttributedString.AddAttribute
                (
                    UIStringAttributeKey.KerningAdjustment,
                    NSObject.FromObject(characterSpacing), new NSRange(0, text.Length - 1)
                );
            }
        }
Exemplo n.º 42
0
        private UIStringAttributes CreateAttributesByFont(ref NSMutableAttributedString text, IBaseFont font, FontIndexPair pair = null, FontTag tag = null)
        {
            UIStringAttributes stringAttributes = new UIStringAttributes {
            };

            //add the font
            stringAttributes.Font = TouchAssetPlugin.GetCachedFont(font);

            //add the color
            if (font.Color != System.Drawing.Color.Empty)
            {
                stringAttributes.ForegroundColor = font.Color.ToNativeColor();
            }

            if (pair != null && tag != null)
            {
                if (tag.FontAction == FontTagAction.Link)
                {
                    CreateLink(ref text, ref stringAttributes, font, pair);
                }
            }

            if (font is Font)
            {
                var extendedFont = font as Font;

                if (stringAttributes.ParagraphStyle == null)
                {
                    stringAttributes.ParagraphStyle = new NSMutableParagraphStyle();
                }

                if (extendedFont.Alignment != TextAlignment.None)
                {
                    UITextAlignment alignment = extendedFont.ToNativeAlignment();
                    stringAttributes.ParagraphStyle.Alignment = alignment;
                }

                //add the lineheight
                stringAttributes.ParagraphStyle.LineSpacing = GetPlatformLineHeight(font.Size, extendedFont.LineHeight);

                stringAttributes.ParagraphStyle.LineBreakMode = extendedFont.ToNativeLineBreakMode();

                stringAttributes.ParagraphStyle.LineHeightMultiple = extendedFont.LineHeightMultiplier.HasValue ? (float)extendedFont.LineHeightMultiplier.Value : 0f;
            }

            return(stringAttributes);
        }
Exemplo n.º 43
0
		public NSAttributedString AttributedStringForParagraph (XElement paragraph)
		{
			var returnValue = new NSMutableAttributedString ();

			// TODO: find stage directions and format them differently
			if (ParagraphIsStageDirection (paragraph)) {
				var stageDirection = new NSAttributedString (TextForParagraph (paragraph),
				                                             font: UIFont.FromName ("Helvetica-LightOblique", 24),
				                                             paragraphStyle: new NSMutableParagraphStyle () { Alignment = UITextAlignment.Center, LineSpacing = 10});
				returnValue.Append (stageDirection);
			} else {
				var speaker = new NSAttributedString (SpeakerForParagraph (paragraph),
	                                                  font: UIFont.FromName ("HoeflerText-Black", 24),
				                                      foregroundColor: UIColor.Brown
				                                      );
				var text = new NSAttributedString (TextForParagraph (paragraph),
				                                   font: UIFont.FromName ("HoeflerText-Regular", 24.0f),
				                                   foregroundColor: UIColor.Black
#if TEST_OTHER_ATTRIBUTES
				                                   ,backgroundColor: UIColor.Yellow,
				                                   ligatures: NSLigatureType.None,
				                                   kerning: 10,
				                                   underlineStyle: NSUnderlineStyle.Single,
				                                   shadow: new NSShadow () { ShadowColor = UIColor.Red, ShadowOffset = new System.Drawing.SizeF (5, 5) },
												   strokeWidth: 5
#endif
				);

				returnValue.Append (speaker, "  ", text);
			}

			if (Paragraphs.IndexOf (paragraph) == SelectedParagraph) {
				returnValue.AddAttribute (UIStringAttributeKey.ForegroundColor, UIColor.White, new NSRange (0, returnValue.Length));
				returnValue.AddAttribute (UIStringAttributeKey.BackgroundColor, UIColor.FromHSB (.6f, .6f, .7f), new NSRange (0, returnValue.Length));
			}

			returnValue.EnumerateAttribute (UIStringAttributeKey.ParagraphStyle, new NSRange (0, returnValue.Length), NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired,
			                                (NSObject value, NSRange range, ref bool stop) => {
				var style = value == null ? new NSMutableParagraphStyle () : (NSMutableParagraphStyle)value.MutableCopy ();
				style.MinimumLineHeight = LineHeight;
				style.MaximumLineHeight = LineHeight;

				returnValue.AddAttribute (UIStringAttributeKey.ParagraphStyle, style, range);
			});

			return returnValue;
		}
Exemplo n.º 44
0
        public void Set(Uri imgUrl, string time, UIImage actionImage,
                        NSMutableAttributedString header, NSMutableAttributedString body,
                        List <Link> headerLinks, List <Link> bodyLinks, Action <NSUrl> webLinkClicked, bool multilined)
        {
            if (imgUrl == null)
            {
                Image.Image = Images.Avatar;
            }
            else
            {
                Image.SetImage(new NSUrl(imgUrl.AbsoluteUri), Images.Avatar);
            }

            Time.Text         = time;
            ActionImage.Image = actionImage;

            if (header == null)
            {
                header = new NSMutableAttributedString();
            }
            if (body == null)
            {
                body = new NSMutableAttributedString();
            }

            Header.AttributedText = header;
            Header.Delegate       = new LabelDelegate(headerLinks, webLinkClicked);

            Body.AttributedText = body;
            Body.Hidden         = body.Length == 0;
            Body.Lines          = multilined ? 0 : 4;
            Body.Delegate       = new LabelDelegate(bodyLinks, webLinkClicked);

            foreach (var b in headerLinks)
            {
                Header.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range);
            }

            foreach (var b in bodyLinks)
            {
                Body.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range);
            }

            AdjustableConstraint.Constant = Body.Hidden ? 0f : 6f;

            AccessibilityHint = header.Value;
        }
Exemplo n.º 45
0
        public static CellSizeHelper Calculate(Post post)
        {
            var photoHeight = (int)(OptimalPhotoSize.Get(new Size()
            {
                Height = post.Media[0].Size.Height, Width = post.Media[0].Size.Width
            },
                                                         (float)UIScreen.MainScreen.Bounds.Width, 180, (float)UIScreen.MainScreen.Bounds.Width + 50));

            var attributedLabel = new TTTAttributedLabel();
            var at = new NSMutableAttributedString();

            at.Append(new NSAttributedString(post.Title, _noLinkAttribute));
            if (!string.IsNullOrEmpty(post.Description))
            {
                at.Append(new NSAttributedString(Environment.NewLine));
                at.Append(new NSAttributedString(Environment.NewLine));
                at.Append(new NSAttributedString(post.Description, _noLinkAttribute));
            }

            foreach (var tag in post.Tags)
            {
                if (tag == "steepshot")
                {
                    continue;
                }
                NSUrl tagUrlWithoutWhitespaces = null;
                var   tagText = tag.Replace(" ", string.Empty);
                if (_tagRegex.IsMatch(tagText))
                {
                    tagUrlWithoutWhitespaces = new NSUrl(tagText);
                }
                var linkAttribute = new UIStringAttributes
                {
                    Link            = tagUrlWithoutWhitespaces,
                    Font            = Constants.Regular14,
                    ForegroundColor = Constants.R231G72B0,
                };
                at.Append(new NSAttributedString($" #{tag}", linkAttribute));
            }

            attributedLabel.Lines = 3;
            attributedLabel.SetText(at);

            var textHeight = attributedLabel.SizeThatFits(new CGSize(UIScreen.MainScreen.Bounds.Width - 15 * 2, 0)).Height;

            return(new CellSizeHelper(photoHeight, textHeight, at));
        }
        private void CreateAttributedString(UILabel control, string html)
        {
            var attr    = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();

            attr.DocumentType = NSDocumentType.HTML;

            var myHtmlData = NSData.FromString(html, NSStringEncoding.Unicode);
            // control.Lines = 0;
            var mutable = new NSMutableAttributedString(new NSAttributedString(myHtmlData, attr, ref nsError));
            var links   = new List <LinkData>();

            control.AttributedText = mutable;

            // make a list of all links:
            mutable.EnumerateAttributes(new NSRange(0, mutable.Length), NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired, (NSDictionary attrs, NSRange range, ref bool stop) =>
            {
                foreach (var a in attrs) // should use attrs.ContainsKey(something) instead
                {
                    if (a.Key.ToString() != "NSLink")
                    {
                        continue;
                    }
                    links.Add(new LinkData(range, a.Value.ToString()));
                    return;
                }
            });

            // Set up a Gesture recognizer:
            if (links.Count <= 0)
            {
                return;
            }
            control.UserInteractionEnabled = true;
            var tapGesture = new UITapGestureRecognizer((tap) =>
            {
                var url = DetectTappedUrl(tap, (UILabel)tap.View, links);
                if (url != null)
                {
                    // open the link:
                    Device.OpenUri(new Uri(url));
                }
            });

            control.AddGestureRecognizer(tapGesture);
        }
Exemplo n.º 47
0
        private NSAttributedString GetAttributedText()
        {
            var mutableAttributedString = new NSMutableAttributedString(Text);

            mutableAttributedString.BeginEditing();

            mutableAttributedString.AddAttributes(GetAttributes(), new NSRange(0, mutableAttributedString.Length));

            // Apply Inlines
            foreach (var inline in GetEffectiveInlines())
            {
                mutableAttributedString.AddAttributes(inline.inline.GetAttributes(), new NSRange(inline.start, inline.end - inline.start));
            }

            mutableAttributedString.EndEditing();
            return(mutableAttributedString);
        }
Exemplo n.º 48
0
        public NSAttributedString GetAttributedString(string text, web_color color)
        {
            Attributes.ForegroundColor = color.ToCGColor();

            // CoreText won't draw underlines for whitespace so draw a transparent dot
            if (text == " ")
            {
                text = ".";
                Attributes.ForegroundColor = new CGColor(0, 0, 0, 0);
            }
            else if (text == null)
            {
                text = "";
            }

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

            // these styles can only be applied to the NSAttributedString
            if (Decoration.HasFlag(font_decoration.font_decoration_linethrough))
            {
                attrString.AddAttribute((NSString)"NSStrikethrough", new NSNumber(1), range);
            }
            if (Decoration.HasFlag(font_decoration.font_decoration_underline))
            {
                attrString.AddAttribute((NSString)"NSUnderline", new NSNumber(1), range);
                attrString.AddAttribute((NSString)"NSUnderlineColor", new NSObject(color.ToCGColor().Handle), range);
            }

            if (Decoration.HasFlag(font_decoration.font_decoration_overline))
            {
            }

            if (Weight > 400)
            {
            #if __MOBILE__
                var boldFontDescriptor = UIKit.UIFont.FromName(FaceName, Size).FontDescriptor.CreateWithTraits(UIKit.UIFontDescriptorSymbolicTraits.Bold);
                var boldFont           = UIKit.UIFont.FromDescriptor(boldFontDescriptor, 0);
                attrString.AddAttribute(UIKit.UIStringAttributeKey.Font, boldFont, new NSRange(0, text.Length));
            #else
                AppKit.NSMutableAttributedStringAppKitAddons.ApplyFontTraits(attrString, AppKit.NSFontTraitMask.Bold, new NSRange(0, text.Length));
            #endif
            }

            return(attrString);
        }
Exemplo n.º 49
0
        internal static NSMutableAttributedString AddCharacterSpacing(this NSAttributedString attributedString, string text, double characterSpacing)
        {
            NSMutableAttributedString mutableAttributedString;

            if (attributedString == null || attributedString.Length == 0)
            {
                mutableAttributedString = text == null ? new NSMutableAttributedString() : new NSMutableAttributedString(text);
            }
            else
            {
                mutableAttributedString = new NSMutableAttributedString(attributedString);
            }

            AddKerningAdjustment(mutableAttributedString, text, characterSpacing);

            return(mutableAttributedString);
        }
        public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
        {
            try
            {
                var cellIdentifier = new NSString("suggestion");
                var cell = tableView.DequeueReusableCell(cellIdentifier) as NoRecentSearchesViewCell ?? new NoRecentSearchesViewCell(cellIdentifier);

                var text = results[indexPath.Row];
                var hitStart = text.IndexOf("[");
                var hitEnd = text.LastIndexOf("]");

                var hitColor = "646265".ToUIColor();
                var textColor = "989898".ToUIColor();

                var defaultAttributes = new UIStringAttributes {
                    ForegroundColor = textColor,
                    Font = UIFont.FromName("Avenir", 18)
                };

                var hitAttributes = new UIStringAttributes {
                    ForegroundColor = hitColor,
                    Font = UIFont.FromName("Avenir-Medium", 18)
                };

                text = text.Remove(hitEnd, 1);
                text = text.Remove(hitStart, 1);

                var attributedString = new NSMutableAttributedString (text);
                attributedString.SetAttributes(defaultAttributes.Dictionary, new NSRange(0, text.Length));
                attributedString.SetAttributes(hitAttributes.Dictionary, new NSRange(0, hitEnd -1));

                cell.TextLabel.AttributedText = attributedString;
  
                //cell.TextLabel.Text = text;
                //cell.TextLabel.Font = UIFont.FromName("Avenir-Book", 14);
                return cell;
            }
            catch(Exception ex)
            {
                Xamarin.Insights.Report(ex);
                var cell = new UITableViewCell();
                cell.TextLabel.Text = results[indexPath.Row];
                cell.TextLabel.Font = UIFont.FromName("Avenir-Book", 14);
                return cell;
            }
        }
Exemplo n.º 51
0
        private void UpdateLinker()
        {
            var d     = new NSMutableAttributedString(Element.Text, Control.Font, Element.TextColor.ToUIColor());
            var label = Element as Shared.LinkerLabel;

            d.AddAttribute(UIStringAttributeKey.ForegroundColor, Element.TextColor.ToUIColor(),
                           new NSRange(0, Element.Text.Length - 1));
            foreach (var matchWord in label.MatchWords)
            {
                var range = new NSRange(matchWord.StartPosition, matchWord.Length);

                d.AddAttribute(UIStringAttributeKey.ForegroundColor, label.LinkColor.ToUIColor(), range);
                d.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
            }

            Control.AttributedText = d;
        }
Exemplo n.º 52
0
        public static NSAttributedString EndingWithTick(this string self, double fontHeight)
        {
            var tick = GetAttachmentString("icDoneSmall", fontHeight);

            var range      = new NSRange(0, 1);
            var attributes = new UIStringAttributes {
                ForegroundColor = UIColor.White
            };

            tick.AddAttributes(attributes, range);

            var result = new NSMutableAttributedString(self);

            result.Append(tick);

            return(result);
        }
Exemplo n.º 53
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            if (View != null && View.Frame.IsEmpty == false)
            {
                InitialHeight = View.Frame.Height;
            }

            CustomButtonStyles.ApplyStyleMainButton(GuiButtonLogIn, LocalizedStrings.Instance.LocalizedString("Button_LogIn"));

            CustomButtonStyles.ApplyStyleNavigationButtonV2(GuiButtonStartFreeTrial, LocalizedStrings.Instance.LocalizedString("Button_StartFreeTrial"));

            GuiTextViewUser.PlaceholderString = LocalizedStrings.Instance.LocalizedString("Placeholder_Username");
            GuiTextViewUser.Cell.Title        = __LogInViewModel.UserName ?? "";
            GuiTextViewUser.LineBreakMode     = NSLineBreakMode.TruncatingHead;

            // ACCOUNT ID DESCRIPTION ...
            // Initialize Account ID description text with link to a Client Area
            NSData             descriptionData = NSData.FromString("Your account ID can be found in the <a style=\"text-decoration:none\" href=\"https://www.ivpn.net/clientarea/login\">Client Area</a> of the website");
            NSDictionary       resultDocumentAttributes;
            NSAttributedString nSAttributed = NSAttributedString.CreateWithHTML(descriptionData, out resultDocumentAttributes);

            NSStringAttributes descTextAttributes = new NSStringAttributes();

            descTextAttributes.Font            = GuiTextAccountIdDescription.Font;      // keep using preconfigured TextField font
            descTextAttributes.ForegroundColor = GuiTextAccountIdDescription.TextColor; // keep using preconfigured TextField color
            descTextAttributes.ParagraphStyle  = new NSMutableParagraphStyle {
                Alignment = NSTextAlignment.Center
            };

            NSMutableAttributedString descriptionString = new NSMutableAttributedString(nSAttributed);

            descriptionString.AddAttributes(descTextAttributes, new NSRange(0, nSAttributed.Length));

            GuiTextAccountIdDescription.AllowsEditingTextAttributes = true;        // it is important
            GuiTextAccountIdDescription.Selectable            = true;
            GuiTextAccountIdDescription.AttributedStringValue = descriptionString; // nSAttributed;
            // ... ACCOUNT ID DESCRIPTION

            GuiButtonLogIn.Hidden = false;

            View.OnApperianceChanged += () =>
            {
                CustomButtonStyles.ApplyStyleNavigationButtonV2(GuiButtonStartFreeTrial, LocalizedStrings.Instance.LocalizedString("Button_StartFreeTrial"));
            };
        }
		public static NSMutableAttributedString GetSearchResultAttributedString (this string result, string searchString)
		{
			var attrString = new NSMutableAttributedString (result);

			attrString.AddAttributes (SearchResultStringAttributes, new NSRange (0, result.Length));

			var index = result.IndexOf (searchString, StringComparison.OrdinalIgnoreCase);

			if (index >= 0 && index + searchString.Length <= result.Length) {

				var range = new NSRange (index, searchString.Length);

				attrString.AddAttributes (SearchResultHighlightStringAttributes, range);
			}

			return attrString;
		}
Exemplo n.º 55
0
        /// <summary>
        /// Creates a styled string as an NSAttibutedString
        /// </summary>
        /// <returns>The styled string.</returns>
        /// <param name="style">TextStyleParameters for styling</param>
        /// <param name="text">Text to style</param>
        /// <param name="startIndex">Style start index</param>
        /// <param name="endIndex">Style end index</param>
        public NSMutableAttributedString CreateStyledString(TextStyleParameters style, string text, int startIndex = 0, int endIndex = -1)
        {
            var attribs = GetStringAttributes(style, DefaultTextSize);

            text = ParseString(style, text);

            if (endIndex == -1)
            {
                endIndex = text.Length;
            }

            var prettyString = new NSMutableAttributedString(text);

            prettyString.SetAttributes(attribs, new NSRange(startIndex, endIndex));

            return(prettyString);
        }
Exemplo n.º 56
0
 private void RefreshDisplayedCreditCount()
 {
     if (CreditsUserLabel != null)
     {
         CreditsUserLabel.Text = SeekiosApp.Helper.CreditHelper.TotalCredits;
         var firstAttributes = new UIStringAttributes
         {
             ForegroundColor = UIColor.FromRGB(98, 218, 115)
         };
         var resultTuple        = SeekiosApp.Helper.StringHelper.GetStartAndEndIndexOfStringInString(Application.LocalizedString("CreditOfferedAmount"), SeekiosApp.Helper.CreditHelper.CreditsOffered);
         var offeredCreditsText = new NSMutableAttributedString(string.Format(Application.LocalizedString("CreditOfferedAmount")
                                                                              , SeekiosApp.Helper.CreditHelper.CreditsOffered));
         offeredCreditsText.SetAttributes(firstAttributes.Dictionary
                                          , new NSRange(resultTuple.Item1, SeekiosApp.Helper.CreditHelper.CreditsOffered.Length));
         CreditsFreeLabel.AttributedText = offeredCreditsText;
     }
 }
Exemplo n.º 57
0
        private static void UpdateUi(ExtendedLabel view, UILabel control)
        {
            var font = UIFont.SystemFontOfSize((view.FontSize > 0) ? (float)view.FontSize : 12.0f);    // regular

            control.Font = font;

            var attrString = new NSMutableAttributedString(control.Text);

            if (view.IsUnderline)
            {
                attrString.AddAttribute(UIStringAttributeKey.UnderlineStyle,
                                        NSNumber.FromInt32((int)NSUnderlineStyle.Single),
                                        new NSRange(0, attrString.Length));
            }

            control.AttributedText = attrString;
        }
        /// <summary>
        /// Updates the UI.
        /// </summary>
        /// <param name="view">
        /// The view.
        /// </param>
        /// <param name="control">
        /// The control.
        /// </param>
        private static void UpdateUi(ExtendedLabel view, UILabel control)
        {
            if (!string.IsNullOrEmpty(view.FontName))
            {
                var font = UIFont.FromName(
                    view.FontName,
                    (view.FontSize > 0) ? (float)view.FontSize : 12.0f);

                if (font != null)
                {
                    control.Font = font;
                }
            }

            if (!string.IsNullOrEmpty(view.FontNameIOS))
            {
                var font = UIFont.FromName(
                    view.FontNameIOS,
                   (view.FontSize > 0) ? (float)view.FontSize : 12.0f);

                if (font != null)
                {
                    control.Font = font;
                }
            }

            var attrString = new NSMutableAttributedString(control.Text);

            if (view.IsUnderline)
            {
                //control.AttributedText = new NSAttributedString(
                //    control.Text,
                //    underlineStyle: NSUnderlineStyle.Single);

                attrString.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attrString.Length));
            }

            if (view.IsStrikeThrough)
            {
                attrString.AddAttribute(UIStringAttributeKey.StrikethroughStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), new NSRange(0, attrString.Length));
            }

            control.AttributedText = attrString;
        }
Exemplo n.º 59
0
		public static NSAttributedString ParseStringForKeywords (ParseableString obj, string str)
		{

			if (String.IsNullOrEmpty (str)) {
				return new NSMutableAttributedString ("");
			}

			NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle ();
			paragraphStyle.LineSpacing = 2;

			NSMutableAttributedString attributedString = new NSMutableAttributedString (str);
			attributedString.BeginEditing ();
			attributedString.AddAttribute (UIStringAttributeKey.ForegroundColor, UIColor.FromRGB (129, 132, 136), new NSRange (0, attributedString.Value.Length));
			attributedString.AddAttribute (UIStringAttributeKey.Font, UIFont.FromName ("Arial", 16), new NSRange (0, attributedString.Value.Length));
			attributedString.AddAttribute (UIStringAttributeKey.ParagraphStyle, paragraphStyle, new NSRange (0, attributedString.Value.Length));

			if (obj.handles == null) {
				List<NSRange> handles = RangedOfStringInString (new NSString ("@"), str, str);
				obj.handles = new List<int> ();
				if (handles.Count > 0) {
					for (int i = 0; i < handles.Count; i++) {
						obj.handles.Add ((int)handles [i].Location);
						obj.handles.Add ((int)handles [i].Length);
					}
				} 
			}
			ChangeColorOfTextInRanges (obj.handles, attributedString);

			if (obj.hashes == null) {
				List<NSRange> hashes = RangedOfStringInString (new NSString ("#"), str, str);
				obj.hashes = new List<int> ();
				if (hashes.Count > 0) {
					for (int i = 0; i < hashes.Count; i++) {
						obj.hashes.Add ((int)hashes [i].Location);
						obj.hashes.Add ((int)hashes [i].Length);
					}
				}
			}
			ChangeColorOfTextInRanges (obj.hashes, attributedString);


			return attributedString;
		}
Exemplo n.º 60
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			string sourceText = @"Source: ";
			NSMutableAttributedString attributedText = new NSMutableAttributedString (@"Wikipedia");
			attributedText.AddAttribute (UIStringAttributeKey.Link, new NSString( @"https://en.wikipedia.org/wiki/Gorilla"), new NSRange (sourceText.Length, attributedText.Length - sourceText.Length));

			attributionTextView.AttributedText = attributedText;

			videoView.Delegate = this;
			videoView.EnableFullscreenButton = true;
			videoView.EnableCardboardButton = true;

			IsPaused = false;
				
			videoView.LoadFromUrl (  NSUrl.FromFilename ("congo.mp4"));

		}