本节内容
设计一个微博APP的PostCell,即关注列表的每一个关注对象。并为用户头像添加右下角的“V”字徽章。
知识点
- UIImage
An object that manages image data in your app.
一个管理图像数据的对象。图像对象是不可改变的,必须是磁盘上已经存在的图像文件或通过程序创建的图像数据。
推荐添加使用PNG或JPEG格式的图像文件。由于PNG图像是无损的,因此尤其推荐在应用中使用PNG格式的图像。
使用下面的方法可以对比两个图像是否一致。
let image1 = UIImage(named: "MyImage")
let image2 = UIImage(named: "MyImage")
if image1 != nil && image1!.isEqual(image2) {
// Correct. This technique compares the image data correctly.
}
- Image 图像
A view that displays an environment-dependent image.
将会返回一个图像视图。
- overlay 叠加
在当前视图上再叠加一个新的视图
- offset 偏移修改器
Offset this view by the specified horizontal and vertical distances.
按指定的水平和垂直距离偏移该视图。
- .clipShape 按形状裁剪
Sets a clipping shape for this view.
将当前视图按照指定形状进行裁剪。
Image(uiImage: UIImage(named: "test.jpg")!)
.clipShape(Circle()) // 切成一个圆形
- .foregroundColor
Sets the color of the text displayed by this view.
设置文本的显示颜色
- spacing 和 padding 的区别
padding是一个格子内的空隙,spacing是格子和格子之间的空隙
实战代码
PostSell.swift
//
// PostSell.swift
// WeiboDemo
//
// Created by EchoSun on 2020/11/29.
//
import SwiftUI
struct PostSell: View {
var body: some View {
HStack(spacing: 5.0) {
// 使用 library 窗口快速添加 ⇧⌘ L
Image(uiImage: UIImage(named: "d0c21786ly1gavj2c0kcej20c8096dh7.jpg")!)
.resizable() // 调整到合适的大小
.scaledToFit() // 按比例缩放
// 下面两个语句顺序很关键,由于图片是矩形的,若这两句顺序颠倒,则最终效果是"直边椭圆形"。
.clipShape(Circle()) // 切成一个圆形
.frame(width:50, height: 50) // 设置大小
//
.overlay(
// 为了进一步简化代码,方便我们快速设置角标,我们将头像右下角的”V“抽象到一个新的视图中。
PostVIPBadge()
// 设置一个偏移量
.offset(x: 16, y: 16)
)
// VStack:纵向排列
// leading: 左对齐
// spacing: 四种间隔
VStack(alignment: .leading, spacing: 5.0) {
Text("用户昵称") // 限制行数
.font(Font.system(size: 16))
.foregroundColor(.red)
.lineLimit(1)
Text("2020-1-1-1")
.font(Font.system(size: 11))
.foregroundColor(.gray)
}
.padding(.leading,10)
Spacer() // 中间填充空间
Button(action: {
print("Click follow button")
}) {
Text("关注")
.font(.system(size: 14))
.foregroundColor(.orange)
.frame(width: 50, height: 26) // 设置frame可以便于画矩形边框,也可以增大按键区域。
.overlay(
RoundedRectangle(cornerRadius: 13)
.stroke(Color.orange,lineWidth: 1) // 绘制轮廓
)
}
}
}
}
struct PostSell_Previews: PreviewProvider {
static var previews: some View {
PostSell()
}
}
PostVIPBadge.swift
//
// PostVIPBadge.swift
// WeiboDemo
//
// Created by EchoSun on 2020/11/29.
//
import SwiftUI
struct PostVIPBadge: View {
var body: some View {
Text("V")
.bold()
.font(Font.system(size: 11))
.frame(width: 15, height: 15)
.foregroundColor(.yellow)
.background(Color.red)
.clipShape(Circle())
.overlay(
RoundedRectangle(cornerRadius: 7.5)
.stroke(Color.white,lineWidth: 1)
)
}
}
struct PostVIPBadge_Previews: PreviewProvider {
static var previews: some View {
PostVIPBadge()
}
}