You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin iOS中为按钮标题添加下划线?

在Xamarin.iOS中为按钮文本添加下划线的实现方案

嘿,要给你的StyleLinkButtonBlack样式按钮加上文本下划线其实很简单,我给你两种靠谱的实现方式,适配不同的iOS版本需求:

方法一:通用富文本方案(兼容所有iOS版本)

这种方式通过NSAttributedString给按钮设置富文本标题,能完美兼容所有iOS版本,同时保留你原来的所有样式设置。直接修改你的扩展方法即可:

public static UIButton StyleLinkButtonBlack(this UIButton button) 
{
    // 保留你原有的样式配置
    button.Font = Styles.SetOpenSansSemiboldFont(Dimensions.medium);
    button.LineBreakMode = UILineBreakMode.WordWrap;
    button.TitleLabel.TextAlignment = UITextAlignment.Center;

    // 新增下划线相关的富文本属性
    var textAttributes = new UIStringAttributes
    {
        ForegroundColor = UIColor.Black,
        UnderlineStyle = NSUnderlineStyle.Single, // 可选样式:Single单下划线、Double双下划线等
        Font = button.Font
    };

    // 将按钮现有标题转为带下划线的富文本并设置回去
    var currentTitle = button.Title(UIControlState.Normal);
    if (!string.IsNullOrEmpty(currentTitle))
    {
        var attributedTitle = new NSAttributedString(currentTitle, textAttributes);
        button.SetAttributedTitle(attributedTitle, UIControlState.Normal);
    }

    return button;
}

注意点:

如果你的按钮标题是动态设置的(比如后续通过SetTitle方法修改),记得要改用SetAttributedTitle来设置,或者把创建富文本的逻辑抽成一个独立方法,确保每次设置标题时都能带上下划线样式。

方法二:iOS 15+专属简洁方案

如果你的App只需要支持iOS 15及以上版本,可以用苹果推出的UIButton.Configuration API来更模块化地管理按钮样式,代码会更简洁:

public static UIButton StyleLinkButtonBlack(this UIButton button) 
{
    var buttonConfig = UIButton.Configuration.PlainButtonConfiguration();
    
    // 通过转换器添加下划线及其他文本样式
    buttonConfig.TitleTextAttributesTransformer = incomingAttrs => 
    {
        var mutableAttrs = incomingAttrs.MutableCopy() as NSMutableAttributedString;
        var fullTextRange = new NSRange(0, mutableAttrs.Length);
        
        mutableAttrs.AddAttribute(UIStringAttributeKey.UnderlineStyle, 
                                  NSNumber.FromInt32((int)NSUnderlineStyle.Single), 
                                  fullTextRange);
        mutableAttrs.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Black, fullTextRange);
        mutableAttrs.AddAttribute(UIStringAttributeKey.Font, Styles.SetOpenSansSemiboldFont(Dimensions.medium), fullTextRange);
        
        return mutableAttrs;
    };

    // 保留原有的换行和对齐设置
    buttonConfig.TitleLineBreakMode = UILineBreakMode.WordWrap;
    buttonConfig.TitleAlignment = UITextAlignment.Center;

    button.Configuration = buttonConfig;
    return button;
}

这种方式的好处是把按钮的所有样式都集中在Configuration中管理,后续修改样式会更方便。

内容的提问来源于stack exchange,提问作者El0din

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:39:31