Coder Social home page Coder Social logo

jaywcjlove / swiftui-example Goto Github PK

View Code? Open in Web Editor NEW
425.0 6.0 33.0 32.91 MB

SwiftUI 示例,技巧和技术集合,帮助我构建应用程序,解决问题以及了解SwiftUI的实际工作方式。

Home Page: https://jaywcjlove.github.io/swiftui-example

License: MIT License

Swift 83.68% Rich Text Format 0.14% Markdown 16.17%
swift swiftui ios swiftui-example example uikit

swiftui-example's Issues

使用 Swift 更改占位符(placeholder)文本颜色

您可以使用属性字符串设置占位符文本。 通过属性传递所需的颜色:

SwiftUI 使用

struct ContentView: View {
    @State var text = ""
    var body: some View {
        ZStack(alignment: .leading) {
            if text.isEmpty { Text("Placeholder").foregroundColor(.red) }
            TextField("", text: $text)
        }
    }
}

iShot2021-05-09 02 37 53

var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
    string: "placeholder text",
    attributes: [NSForegroundColorAttributeName: UIColor.yellow]
)

Swift 3+ 使用以下内容:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "placeholder text",
    attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)

Swift 4.2 使用以下内容:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "placeholder text",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)

退出应用

Button(action: {
    // 退出应用
    NSApplication.shared.terminate(self)
}, label: {
    Image(systemName: "clock")
    Text("Click Me")
})

对数组 Array 的操作

insert 插入

var myArray = ["Steve", "Bill", "Linus", "Bret"]
myArray.insert("jaywcjlove", at: 1)
print(myArray)
// ["Steve", "jaywcjlove", "Bill", "Linus", "Bret"]

append 添加到末尾

var myArray = ["Steve", "Bill", "Linus", "Bret"]
myArray.append("wcj")
print(myArray)
// ["Steve", "Bill", "Linus", "Bret", "wcj"]

合并数组

var array1 = [1,2,3,4,5]
let array2 = [6,7,8,9]

let array3 = array1+array2
print(array3)
array1.append(contentsOf: array2)
print(array1)

删除所有 Core Data 数据

let entities = PersistenceController.shared.container.managedObjectModel.entities
for entity in entities {
    if ((entity.name) != nil) {
        let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity.name!)
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)

        do {
            try viewContext.execute(deleteRequest)
            try viewContext.save()
        } catch {
            print ("There was an error")
        }
    }
}

点击展开下拉菜单 Menu

image

Menu("PDF") {
    Button("Open in Preview", action: { })
    Button("Save as PDF", action: { })
}
.menuStyle(BorderlessButtonMenuStyle())

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Other Branches

These updates are pending. To force PRs open, click the checkbox below.

  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update peaceiris/actions-gh-pages action to v4

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v3
  • actions/setup-node v3
  • peaceiris/actions-gh-pages v3
  • ncipollo/release-action v1
npm
package.json
  • idoc ^1.29.0

  • Check this box to trigger a request for Renovate to run again on this repository

画三角形

struct Triangle: Shape {
    func path(in rect: CGRect)-> Path {
        var path = Path()

        path.move(to: CGPoint(x: rect.midX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.midX, y: rect.minY))

        return path
    }
}

使用

Triangle()
    .fill(Color.green)
    .frame(width: 100, height: 100, alignment: .center)

删除不再支持的旧模拟器以清理一些空间

除了获得 Mac)是从 Mac App Store 下载 Xcode。

如果您已经使用 Xcode 一段时间了,您应该删除不再支持的旧模拟器以清理一些空间。 使用以下终端命令删除旧模拟器:

$ xcrun simctl delete unavailable

如何将一个View 作为变量传递给另一个View struct

https://stackoverflow.com/a/63937440/1334703

struct ContainerView<Content: View>: View {
    let content: Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content()
    }
    
    var body: some View {
        content
    }
}

这不仅允许您将简单的Views放入其中,而且由于使用@ViewBuilder,还可以使用if-else和switch-case块:

使用示例 1:

struct SimpleView: View {
    var body: some View {
        ContainerView {
            Text("SimpleView Text")
        }
    }
}

使用示例 2:

struct IfElseView: View {
    var flag = true
    
    var body: some View {
        ContainerView {
            if flag {
                Text("True text")
            } else {
                Text("False text")
            }
        }
    }
}

使用示例 3:

struct SwitchCaseView: View {
    var condition = 1
    
    var body: some View {
        ContainerView {
            switch condition {
            case 1:
                Text("One")
            case 2:
                Text("Two")
            default:
                Text("Default")
            }
        }
    }
}

如果您想要一个贪婪的容器,它将占用所有可能的空间(与上面的容器只声明其子视图所需的空间相反),这里是:

struct GreedyContainerView<Content: View>: View {
    let content: Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content()
    }
    
    var body: some View {
        Color.clear
            .overlay(content)
    }
}

结构 struct 只能从协议继承

结构只能从协议继承(如果正确的话)。 不能从基本结构继承,所以您不能做

struct Resolution {
    var width = 0
    var height = 0
}

struct MyStruct: Resolution { ... }  // ERROR!

因此,有两个选择。 第一种是改用类。 第二个是重构代码以使用协议。

因此,有一些常用方法,则可以执行以下操作:

protocol PixelContainer {
   var width: Int { get }
   var height: Int { get }
}

extension PixelContainer {
    var count: Int { return width * height }
}

struct Resolution: PixelContainer {
    var width = 10
    var height = 20
}

let numPixels = Resolution().count  // Legal

循环 for..in, map, filter

实例

let values = [2.0, 4.0, 5.0, 7.0]
var squares: [Double] = []
for value in values {
   squares.append(value * value)
}
print(squares) // [4.0, 16.0, 25.0, 49.0]
let values = [2.0,4.0,5.0,7.0]
let squares2 = values.map({ (value: Double) -> Double in
  return value * value
})
print(squares2) // [4.0, 16.0, 25.0, 49.0]
let values = [2.0,4.0,5.0,7.0]
let squares2 = values.map { value in 
  value * value
}
print(squares2) // [4.0, 16.0, 25.0, 49.0]
let values = [2.0,4.0,5.0,7.0]
let squares = values.map { $0 * $0 }
print(squares) // [4.0, 16.0, 25.0, 49.0]
let scores = [0,28,124]
let words = scores.map {
    NumberFormatter.localizedString(from: NSNumber(value: $0), number: .spellOut)
}
print(words) // ["zero", "twenty-eight", "one hundred twenty-four"]
let milesToPoint = ["point1":120.0, "point2": 50.0,"point3": 70.0]
let kmToPoint = milesToPoint.map { name,miles in miles * 1.6093 }
print(kmToPoint) // [112.651, 193.11599999999999, 80.465]
let lengthInMeters: Set = [4.0, 6.2, 8.9]
let lengthInFeet = lengthInMeters.map { meters in meters * 3.2808 }
print(lengthInFeet) // [29.199120000000004, 20.340960000000003, 13.1232]
let digits = [1, 4, 5, 10, 15]
let even = digits.filter { (number) -> Bool in return
   number % 2 == 0
}
print(even) // [4, 10]

// -----> 简写 <------

let digits = [1, 4, 10, 15]
let even = digits.filter { $0 % 2 == 0 }
print(even) // [4, 10]

实例

func hashtags(in string: String) -> [String] {
    let words = string.components(
        separatedBy: .whitespacesAndNewlines
    )
    // 通过过滤器,我们可以删除所有不符合条件的元素
    // 给定的要求,在这种情况下,那些没有开始的要求
    // 以前置的"#"字字符:
    return words.filter { $0.starts(with: "#") }
}

let tags = hashtags(in: "#Swift by Hello #Basics")
print(tags) // ["#Swift", "#Basics"]

实例

func hashtags(in string: String) -> [String] {
    let words = string.components(
        separatedBy: .whitespacesAndNewlines
    )
    let tags = words.filter { $0.starts(with: "#") }
    // 使用'map',我们可以将闭包作为转换将值序列转换为新的值数组:
    return tags.map { $0.lowercased() }
}

let strings = [
    "I'm excited about #SwiftUI",
    "#Combine looks cool too",
    "This year's #WWDC was amazing"
]
let tags = strings.map { hashtags(in: $0) }
print(tags) // [["#swiftui"], ["#combine"], ["#wwdc"]]

Optional to String

func convertToInt(_ string: String?) -> Int? {
    return string.flatMap(Int.init)
}

let str = convertToInt("23")
print(str) // Optional(23)

print(str ?? "") // 23

guard let value = str else {return}
print(value) // 23

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.