티스토리 뷰

#NSMutableAttributedString #Attribute #CustomCollectionViewCell #Insert Image into String #Set Color of Image #Paragraph Style #Kingfisher Indicator #KingFisher
프로젝트 코드 : https://github.com/LeeGwangYong/iOS_swift/tree/master/FaceBook
참고 사이트 : https://www.youtube.com/watch?v=NJxb7EKXF3U&list=PL0dzCUj1L5JHDWIO3x4wePhD8G4d1Fa6N

1. CustomCollectionViewCell 구현
영상의 constraint를 추가한 것과 같이 Label, TextView, ImageView의 @IBOutlet을 생성
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var profileImg: RoundedImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var statusTextView: UITextView!
    @IBOutlet weak var feedImageView: UIImageView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func awakeFromNib() {
        setupCell()
    }
 
    func setupCell(){
        self.contentView.translatesAutoresizingMaskIntoConstraints = false
        widthConstraint.constant = UIScreen.main.bounds.size.width
      
        self.backgroundColor = UIColor.white
        statusTextView.font = UIFont.systemFont(ofSize: 14)
        statusTextView.isScrollEnabled = false
        feedImageView.contentMode = .scaleAspectFill
        feedImageView.layer.masksToBounds = true
        feedImageView.isUserInteractionEnabled = true    
    }
cs
2. Object Model 만들기
ㄱ. Post.swift 생성
1
2
3
4
5
6
7
8
9
10
import Foundation
 
struct Post
{
    let name: String!
    let time: String!
    let statusText: String!
    let profileImg: String!
    let statusImgURL: String!
}
cs
ㄴ. ViewController 수정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    var postList = [Post]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout{
            flowLayout.estimatedItemSize = CGSize(width: 200, height: 400)
        }
        setupFeedController()
    }
    
    func setupFeedController(){
        collectionView?.backgroundColor = UIColor(white: 0.95, alpha: 1)
        collectionView?.alwaysBounceVertical = true
        
        
        postList.append(Post(name: "버즈 라이트이어",
                             time: "11월 22일 오후 9:30",
                             statusText: "오늘은 하품하는 개를 가져왔습니다.",
                             profileImg: "buzz",
                             statusImgURL: "https://i.pinimg.com/564x/4e/42/ee/4e42eeb02c1217a676064f28056245d4.jpg"))
            
        postList.append(Post(name: "우디", time: "11월 22일 오후 9:30", statusText: """
            난 너의 친구야
            영원한 친구야
            너 어렵고 힘들때
            누구에게 의지하고 싶을때
            내가 있다는 사실 잊지마
            그래 난 너의 친구야
            예 영원한 친구야
            난 너의 친구야
            영원한 친구야
            """, profileImg:"woody", statusImgURL: "https://i.pinimg.com/564x/23/5c/28/235c280ec0749d4fa510c399281aedcd.jpg"))
    }

cs

ㄷ. CustomCollectionCell 수정

하나의 Label에 두 줄의 Text를 만들고, 각각 속성을 부여하기

NSMutableAttributedString 사용, NSMutableAttributedString Attribute 부여

1
2
let attributedString = NSMutableAttributedString(string: name, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])
let timeAttributedString = NSMutableAttributedString(string: "\n" + time + " • ", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)])    
cs

AttributedString에 이미지 삽입하기

Insert Image into String, Set Color of Image

1
2
3
4
5
6
7
//Attach Image
let attachmentImage = NSTextAttachment()
attachmentImage.image = 
#imageLiteral(resourceName:"earth").withRenderingMode(UIImageRenderingMode.alwaysTemplate)
// .withRenderingMode(UIImageRenderingMode.alwaysTemplate)를 이용하여 이미지의 색상을 임의대로 변경이 가능
attachmentImage.bounds = CGRect(x: 0, y: -1, width: 10, height: 10)
let attributedImage = NSAttributedString(attachment: attachmentImage)
cs

문단 간격주기

1
2
3
4
//Paragraph Style 문단 간격
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
attributedString.addAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle], range: NSMakeRange(0, attributedString.string.count))
cs

Kingfisher Indicator, KingFisher 사용

1
2
3
4
5
import UIKit

feedImageView.kf.indicatorType = .activity
let url = URL(string: statusImgURL)
feedImageView.kf.setImage(with: url)
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import UIKit
import Kingfisher
 
class FeedCollectionViewCell: UICollectionViewCell {    
    var post:Post?{
        didSet{
            guard let name = post?.name else {return}
            guard let time = post?.time else {return}
            guard let statusText = post?.statusText else {return}
            guard let profile = post?.profileImg else {return}
            guard let statusImgURL = post?.statusImgURL else {return}
          
            let attributedString = NSMutableAttributedString(string: name, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])
            let timeAttributedString = NSMutableAttributedString(string: "\n" + time + " • ", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)])
            
            //Attach Image
            let attachmentImage = NSTextAttachment()
            attachmentImage.image = #imageLiteral(resourceName: "earth").withRenderingMode(UIImageRenderingMode.alwaysTemplate)
            attachmentImage.bounds = CGRect(x: 0, y: -1, width: 10, height: 10)
            let attributedImage = NSAttributedString(attachment: attachmentImage)
            
            timeAttributedString.append(attributedImage)
            timeAttributedString.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.lightGray], range: NSMakeRange(0, timeAttributedString.string.count))
            
            //Paragraph Style 문단 간격
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 4
            attributedString.addAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle], range: NSMakeRange(0, attributedString.string.count))
            
            attributedString.append(timeAttributedString)
          
            nameLabel.attributedText = attributedString
            profileImg.image = UIImage(named: profile)
            statusTextView.text = statusText
            
            feedImageView.kf.indicatorType = .activity
            let url = URL(string: statusImgURL)
            feedImageView.kf.setImage(with: url)
        }
    }
cs
Tip. 3G나 네터워크 환경이 좋지않은 상황에 대해 테스트할 때 'Network Link Conditioner'를 이용하면 됩니다.


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함