ios - Swift - 如何在设置后更改 UIButton 的 NSMutableAttributedString 的颜色
问题描述
我有 2UIButtons
和它们titles
,colors
最初是使用NSMutableAttributedString
. 文本为2 行文本
我有一个自定义UISegmentedControl
,当切换段时,我只需要更改按钮的颜色。我现在这样做的方式颜色确实会改变,但是当发生这种情况时会出现难看的闪烁,因为实际的文本会再次设置。我只需要颜色的平滑过渡
var selectedSegmentIndex = 0 {
didSet {
layoutIfNeeded()
UIView.animate(withDuration: 0.1) {
self.setTextForFollowersButton()
self.setTextForFollowingButton()
self.layoutIfNeeded()
}
}
}
如何仅更改按钮的颜色NSMutableAttributedString
?
按钮代码:
var numOfFollowers = 0 {
didSet {
setTextForFollowersButton()
}
}
var numOfFollowing = 0 {
didSet {
setTextForFollowingButton()
}
}
lazy var followersButton: UIButton = {
let button = UIButton.init(type: .system)
// ...
return button
}()
lazy var followingButton: UIButton = {
let button = UIButton.init(type: .system)
//...
return button
}()
func setTextForFollowersButton() {
let button = self.followersButton
let buttonText = "Following\n\(String(numOfFollowing))" as NSString
// other code for 2 lines of text
var color = UIColor.blue
if selectedSegmentIndex == 0 {
color = UIColor.blue
} else {
color = UIColor.gray
}
let attrString1 = NSMutableAttributedString(string: substring1,
attributes: [NSMutableAttributedString.Key.font:
UIFont.boldSystemFont(ofSize: 16),
NSMutableAttributedString.Key.foregroundColor: color])
let attrString2 = NSMutableAttributedString(string: substring2,
attributes: [NSMutableAttributedString.Key.font:
UIFont.boldSystemFont(ofSize: 14),
NSMutableAttributedString.Key.foregroundColor: color])
attrString1.append(attrString2)
button.setAttributedTitle(attrString1, for: [])
}
func setTextForFollowingButton() {
let button = self.followingButton
let buttonText = "Following\n\(String(numOfFollowing))" as NSString
// other code for 2 lines of text
var color = UIColor.blue
if selectedSegmentIndex == 0 {
color = UIColor.gray
} else {
color = UIColor.blue
}
let attrString1 = NSMutableAttributedString(string: substring1,
attributes: [NSMutableAttributedString.Key.font:
UIFont.boldSystemFont(ofSize: 16),
NSMutableAttributedString.Key.foregroundColor: color])
let attrString2 = NSMutableAttributedString(string: substring2,
attributes: [NSMutableAttributedString.Key.font:
UIFont.boldSystemFont(ofSize: 14),
NSMutableAttributedString.Key.foregroundColor: color])
attrString1.append(attrString2)
button.setAttributedTitle(attrString1, for: [])
}
解决方案
您应该在内部插入UIView.animate
函数DispatchQueue.main.async {}
以进行平滑过渡。始终建议在主线程上异步制作任何类型的 UI 动画。
推荐阅读
- c# - 在 ViewModel 中添加 Id 时自动映射器异常
- python - sklearn ColumnTransformer 不适用于熊猫数据框
- php - 更新 Buddypress 用户的 xprofile 输入
- reporting-services - SSRS - 试图强制两个 tablixes 与图表和隐藏列对齐
- wordpress - header.php 中的透明导航
- javascript - 在 React 中使用绑定到来自 LitElement 的属性
- xslt - xslt 通过子字符串删除重复值
- java - setCellValue(String value) throws java: cannot access java.time.LocalDate class file for java.time.LocalDate not found
- c# - 自定义窗口镶边时是否可以保留普通按钮?
- leaflet - 如何更改 bindPopup 的行为