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

iOS 17 Swift:XIB创建的UIButton标题无法居中异常

UIButton标题对齐异常问题解决

问题描述

通过XIB创建UIButton并关联至UIViewController,按钮标题仅在Xcode直接运行APP时能正常居中,退出后重新打开APP(不通过Xcode启动)则始终左对齐。已尝试设置self.btnContinueSignIn.contentHorizontalAlignment = .center但无效,XIB中EdgeInsets均设为0,0,0,0,标题通过以下代码设置:

let title = NSAttributedString(string: "Continue", attributes: [NSAttributedString.Key.foregroundColor: .red])
btnContinueSignIn.setAttributedTitle(title, for: .normal)

解决方法

  • 直接强制设置标题标签的对齐方式:
    在设置富文本标题的代码后,添加一行:
    btnContinueSignIn.titleLabel?.textAlignment = .center
    
  • 从XIB层面双重确认:
    1. 选中按钮,在「Attributes Inspector」中把「Content Horizontal Alignment」设为「Center」
    2. 展开按钮的「Title Label」子控件,将其「Text Alignment」也设为「Center」
  • 为富文本添加显式段落样式:
    创建富文本时,明确指定居中对齐的段落样式,避免系统默认样式干扰:
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    let title = NSAttributedString(string: "Continue", attributes: [
        NSAttributedString.Key.foregroundColor: UIColor.red,
        NSAttributedString.Key.paragraphStyle: paragraphStyle
    ])
    btnContinueSignIn.setAttributedTitle(title, for: .normal)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:03:10