UILabel内的子视图对齐。 Xamarin IOS

时间:2017-09-25 12:35:51

标签: xamarin.ios uilabel

在这段代码中,我试图在UILabel中的特定单词上方添加tapFields(UIViews)。正确计算每个tapField的宽度,高度,X和Y(也适用于多行文本)。问题是所有字段都忽略了x和y,它们都变成了MessageLabel的左上角:(

我设法理解 - 它发生的原因是MessageLabel.Frame是(0,0,0,0)但我不知道如何解决它。

public CGRect getTapRectForError(NSMutableAttributedString text, NSRange range, float maxWidth)
    {
        var textStorage = new NSTextStorage();
        textStorage.SetString(text);
        var textContainer = new NSTextContainer(new CGSize(4000, 400));
        var layoutManager = new NSLayoutManager();
        layoutManager.AddTextContainer(textContainer);
        textStorage.AddLayoutManager(layoutManager);
        textContainer.LineFragmentPadding = 0;
        var glyphRange = layoutManager.GlyphRangeForCharacterRange(range);
        var glyphRect = layoutManager.BoundingRectForGlyphRange(range, textContainer);

        return glyphRect;
    }

    protected void OnViewTapped(UIGestureRecognizer sender)
    {
        var a = 1;
    }

    public BubbleCell SetupErrors(BubbleCell cell, NSIndexPath indexPath, GrammarCheckResultJson errors)
    {
        if (errors.errors != null)
        {
            var labelText = new NSMutableAttributedString(cell.MessageLabel.Text, underlineStyle: NSUnderlineStyle.Single);

            var Attributes = new UIStringAttributes
            {
                ForegroundColor = UIColor.FromRGB(255, 230, 58),
                UnderlineColor = UIColor.FromRGB(255, 230, 58),
            };

            foreach (ErrorJson error in errors.errors)
            {
                labelText.AddAttributes(Attributes.Dictionary, new NSRange(error.offset, error.length));
                var glyphRect = getTapRectForError(labelText, new NSRange(error.offset, error.length), (float)error.length);
                UIView eView = new UIView(glyphRect);

                eView.AddGestureRecognizer(new UITapGestureRecognizer(OnViewTapped));

                cell.MessageLabel.AddSubview(eView);
            }

            cell.MessageLabel.AttributedText = labelText;
        }
        return cell;
    }

0 个答案:

没有答案