首先让我们来看下要实现的效果
可以看到头条的小号组件里面包含三部分。第一部分是底图,第二部分app名称,第三部分是文章标题。
下面我要讲的是三个重要控件:

这控件是个布局控件,里面所有的子控件都按顺序Z方向排列,也就是从屏幕里到屏幕外排列。
Image上个课程讲过这个控件是展示图片,不过上次讲的是展示iOS系统图片。这次我们讲的是如何展示外部资源图片。为了最简单,这里把下载好的图片放在Assets.xcassets里,并且命名为toutiao。
那么你在展示的时候只需要
Image("toutiao")
即可。另外,还要设置图片的展示模式
Image("toutiao") .resizable() .aspectRatio(contentMode: .fill)
如果想要在切割的话可以这样
Image("toutiao") .resizable() .aspectRatio(contentMode: .fill) .clipped()
Text
上次也讲过此控件,是展示的文字,不过上次讲的是用苹果设置好的字号。这次我们讲的是自定义字号
Text("今日头条") .font(Font.system(size: 20))
另外一个就是标题为两行,这个要怎么设置?请看
Text("吸猫成瘾,养猫“致贫”?年轻人催热...") .font(Font.system(size: 19)) .fontWeight(.bold) .lineLimit(2)
整个下来的展示效果如下
所有代码如下:
struct ContentView: View { let widgetWidth:CGFloat = 180.0 var body: some View { ZStack() { Image("toutiao") .resizable() .aspectRatio(contentMode: .fill) .clipped() .frame(width: widgetWidth, height: widgetWidth) VStack(alignment: .trailing){ Text("今日头条") .font(Font.system(size: 20)) .fontWeight(.bold) .foregroundColor(.white) .padding(.all, 10) Spacer() Text("吸猫成瘾,养猫“致贫”?年轻人催热...") .font(Font.system(size: 19)) .fontWeight(.bold) .lineLimit(2) .foregroundColor(.white) .padding(.all, 10) } } .frame(width: widgetWidth, height: widgetWidth) .background(Color.black) .cornerRadius(30) }}