在Swift中的View Controller外部动态更改文本元素的属性



我是Swift和移动开发的新手,最近我一直在尝试创建一段可以在IOS应用程序上独立工作的代码。我的目标是创建一个框架,可以操作所有应用程序中的文本样式。

我一直纠结于如何访问和动态更改视图控制器中文本元素的属性。

有可能创建一个可以查看视图控制器内部并动态更改样式的框架吗?

到目前为止,我所实现的是使用在视图控制器之外编写的函数来操纵字体样式和颜色(计划稍后将其转储到框架中(。

这是我学习swift的第三天,很抱歉有任何愚蠢的代码或问题。我搜索了很多关于如何动态访问视图控制器中的元素的内容,但没有找到任何内容。。

这是我的代码

//
//  ContentView.swift
//  Swift-UI-Test
//
//  Created by Vikas Nair on 08/05/21.
//
import SwiftUI
struct ContentView: View {
@StateObject var stateObject = TestObject()
var body: some View {
VStack(spacing: 20){
Text("Vikku Here")
.foregroundColor(changeBkColor(color: stateObject.color))
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.font(.system(size:CGFloat(textsize(text_size: stateObject.font_size)) ))
Button(action: {

stateObject.color = 2
stateObject.font_size = "med"

}) {
Text("Press")
.frame(width: 60, height: 60)
.foregroundColor(Color.black)
.background(Color.blue)
.clipShape(Circle())
}.buttonStyle(PlainButtonStyle())

Button(action: {

stateObject.color = 3
stateObject.font_size = "big"

}) {
Text("Press")
.frame(width: 60, height: 60)
.foregroundColor(Color.black)
.background(Color.blue)
.clipShape(Circle())
}.buttonStyle(PlainButtonStyle())

}
}
}
class TestObject: ObservableObject {
@Published var color: Int = 1
@Published var font_size: String = "small"
}
func changeBkColor(color: Int) -> Color
{
if(color == 1)
{
return Color.red;
}
else if(color == 2)
{
return Color.green;
}
else if(color == 3)
{
return Color.blue;
}
else
{
return Color.black;
}
}

func textsize(text_size: String)-> Float
{
if(text_size == "big")
{
return 60.0;
}
else if(text_size == "med")
{
return 35.0;
}
else if(text_size == "small")
{
return 20.0;
}
else
{
return 10.0;
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

以下是我要做的:

  1. @StateObject var stateObject = TestObject()更改为@EnvironmentObject var testObject: TestObject
  2. 去掉changeBkColor(color:)。你不需要它
  3. TestObjectcolor属性设置为Color,如下所示:@Published var color: Color = Color.red
  4. .foregroundColor(changeBkColor(color: stateObject.color))更改为.foregroundColor(testObject.color)
  5. SceneDelegate中存储对TestObject的引用,并在SceneDelegatescene(_:willConnectTo:options:)函数中设置.environmentObject,如下所示:
static let testObject = TestObject()

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView()
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(SceneDelegate.testObject)) // <-- Here
self.window = window
window.makeKeyAndVisible()
}
}

然后,只需将TestObjectcolor属性设置为Color即可更改文本的颜色。

最新更新