iOS 17 Swift:XIB创建的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层面双重确认:
- 选中按钮,在「Attributes Inspector」中把「Content Horizontal Alignment」设为「Center」
- 展开按钮的「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
相关产品推荐
相关产品推荐

