最终效果图:

项目地址:github.com/Paganarchitect/facebook_newsFeed.git
第一部分搭建基本UI,用到了UICollectionView和NSLayoutConstraint的知识。看下这部分完成后:

#1 搭建基本框架,注册cell,设置collectionView数据源和代理

1.删掉storyboard,并把删掉Main Interface里的main。将ViewController改名为FeedController,subclass of UICollectionViewController。


2.搭建基本框架。需说明的是,UICollectionViewFlowLayout是UICollectionViewLayout的默认形式。

3.设定navigation bar,navigation bar titleText及UICollectionView的颜色。
--继续在AppDelegate.swift里,添加代码,设置navigation bar和bar title text的颜色。

--在FeedController.swift里,将bar title text设置为“Facebook News Feed”,collectionView的背景颜色设置为浅灰。

运行一下,现在status bar的颜色还是黑色。想要把它也变成和navigationbartitle的颜色一样,怎么办?

--在Info.plist里,添加一个property--status bar based on view controller appearance,将这个布尔值设为No,这意味着application对status bar的设置高于view controller对status bar的设置。运行一下,status bar的颜色也变成了白色,哈哈。


4.注册collectionViewCell
--新建文件命名为FeedCell

--回到FeedViewController.swift中,

5.添加数据源和代理方法,并设置垂直方向的反弹为YES


#2 添加nameLabel和profileImageView
1.添加nameLabel和profileImageView并加约束.需要说明的是translatesAuthoresizingMaskIntoConstraints属性默认是True,这里我们设置为NO,不添加隐含constraint,这样才能让手动添加的constraint起作用。

当然,也可以添加一个方法,使得代码看起来更简洁!这个方法有两个参数,format和views;先声明一个字典;再对views进行遍历。

运行一下,现在是这样的

2.填充图片,拖图片进来,并添加代码

3.修改label。这里,需要解释以下两点:
--关于numberOfLines:label默认只显示一行,通过设置numberOfLines可以改变行数。但是如果设置为0,则告诉文本不管占多少行,都显示出来。
--关于NSAttributedString富文本字符串。使用场景:设置文字样式和设置段落样式。可以分为NSAttributedString和NSMutableAttributedString两种。在使用中通过将AttributedString赋值给控件的attributedText属性来添加文字样式。有属性的控件有UILabel、UITextField和UITextView。

#3 添加feedTextView,feedImageView和likeCommentsLabel,和dividerLineView
1.在FeedController.swift里,将cell的高度改为450;接着,修改nameLabel的约束,与superview的垂直间距为8 points


2.添加feedTextView,并加约束

3.添加feedImageView,并加约束。这里解释一下masksToBounds属性,它用来防止子元素大小溢出父元素。因为上面我们的contentMode设置成的是scaleAspectFill,所以这里需要将maskToBounds属性设置为true,防止图片溢出。

4.添加likeCommentsLabel,dividerLineView。太简单,不细说。
运行一下,现在是这样的!

#4 添加button

因为这三个button构造基本一样,偷个懒,起一个与这段代码功能相对应的名字,封装成一个新的方法。声明类的类型方法(Type Methods),在方法的关键字func前加上关键字class。

注意button的水平约束,每个button的宽度占superview宽度的1/3。但是VFL不能实现multiplier怎么办?可以让likeButton,commentButton的宽度是shareButton的宽度。

运行一下,现在是这样的:

#5 处理横屏布局
手动调用invalidateLayout方法以更新布局对象,此方法会强制生成新layout。(需要注意invalidateLayout与reloadData的区别,在移动,添加或者删除item的时候,使用invalidateLayout,而如果只是datasource中的数据有更新,这时需要使用reloadData


第一部分结束。
网友评论