SwiftUI实现带圆角自定义颜色按钮时文字不显示问题求助
问题原因与解决方法
问题出在你使用的.overlay修饰符上——它会把你绘制的圆角矩形叠加在按钮的文字内容上层,完全遮挡住了文字,导致看不到按钮文本。
修正后的代码方案
你需要将背景填充部分放到.background修饰符中(该修饰符会在按钮内容下层绘制视图,不会遮挡文字),描边部分可以保留在.overlay或者和填充合并:
方案一:分离背景与描边
Button(shoppingListItem.text) { removeFromShoppingList(itemId: shoppingListItem.item_id) } .background( // 填充背景放在下层,不遮挡文字 RoundedRectangle(cornerRadius: 20, style: .continuous) .fill(Color("ShoppingListItemColor")) ) .overlay( // 描边放在上层,不会挡住文字 RoundedRectangle(cornerRadius: 20) .stroke(Color.secondary, lineWidth: 2) )
方案二:合并背景与描边(更简洁)
Button(shoppingListItem.text) { removeFromShoppingList(itemId: shoppingListItem.item_id) } .background( RoundedRectangle(cornerRadius: 20, style: .continuous) .fill(Color("ShoppingListItemColor")) .stroke(Color.secondary, lineWidth: 2) )
这样修改后,按钮的文字就会正常显示,同时保留你需要的圆角和自定义颜色样式。
内容的提问来源于stack exchange,提问作者AntonSack
相关产品推荐
相关产品推荐

