monotouch NSMutableAttributedString AddAttribute

时间:2013-12-02 16:24:49

标签: c# xamarin.ios nsmutableattributedstring

我正在尝试使用4个基本按钮(粗体,斜体,下划线+颜色)来创建一个富文本编辑器工具栏,这是我实际拥有的:

public override UIView InputAccessoryView
{
    get
    {
        UIToolbar toolbar = new UIToolbar(new RectangleF(0, 0, 320, 30));

        var fixedSpace = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace, null)
        {
            Width = 26
        };
        var flexibleSpace = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null);

        boldItem = new UIBarButtonItem("B", UIBarButtonItemStyle.Plain, (o, e) => { GoBold(); });
        italicItem = new UIBarButtonItem("I", UIBarButtonItemStyle.Plain, (o, e) => { GoItalic(); });
        underlineItem = new UIBarButtonItem("U", UIBarButtonItemStyle.Plain, (o, e) => { GoUnderlined(); });
        redItem = new UIBarButtonItem("R", UIBarButtonItemStyle.Plain, (o, e) => { GoRed(); });
        toolbar.Items = new UIBarButtonItem[] { underlineItem, fixedSpace, italicItem, flexibleSpace, boldItem, fixedSpace, redItem };

        return toolbar;
    }
}

protected NSRange GetTextRange()
{
    return new NSRange(
        textField.GetOffsetFromPosition(textField.BeginningOfDocument, textField.SelectedTextRange.start),
        textField.GetOffsetFromPosition(textField.SelectedTextRange.start, textField.SelectedTextRange.end)
    );
}

protected void GoItalic()
{
    NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);
    text.AddAttribute(CTStringAttributeKey.Font, UIFont.ItalicSystemFontOfSize(20f), GetTextRange());
    textField.AttributedText = text;
}

protected void GoUnderlined()
{
    NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);


    text.AddAttribute(CTStringAttributeKey.UnderlineStyle, new NSNumber((int) NSUnderlineStyle.Single), GetTextRange());

    //text.AddAttribute(CTStringAttributeKey.UnderlineStyle, new NSNumber(NSUnderlineStyle.Single as int), GetTextRange());

    textField.AttributedText = text;
}

protected void GoBold()
{
    NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);
    text.AddAttribute(CTStringAttributeKey.Font, UIFont.BoldSystemFontOfSize(20f), GetTextRange());
    textField.AttributedText = text;
}

protected void GoRed()
{
    NSMutableAttributedString text = new NSMutableAttributedString(textField.AttributedText);
    text.AddAttribute(CTStringAttributeKey.UnderlineColor, UIColor.Red, GetTextRange());
    textField.AttributedText = text;
}

Bold和Italic的效果很好,但没有办法制作下划线和颜色:/,我已经成功地用一个糟糕的演员来强调我的选择,但我宁愿知道应该怎么做。

似乎我遇到了一个转换问题,因为 NSUnderlineStyle.Single 会返回一个预期对象的枚举,颜色也是如此

0 个答案:

没有答案