[swift] SDWebImage를 사용하여 이미지 다운로드 중에 이미지에 캡션을 추가하는 방법은 무엇인가요?
import SDWebImage
// 이미지 다운로드 및 설정
let imageView = UIImageView()
// 이미지 URL
let imageUrl = URL(string: "https://example.com/image.jpg")
// SDWebImage를 사용하여 이미지 다운로드
imageView.sd_setImage(with: imageUrl) { (image, error, cacheType, imageUrl) in
// 이미지 다운로드가 완료되면 캡션을 추가합니다.
if let image = image {
let captionLabel = UILabel()
captionLabel.text = "이미지 캡션"
captionLabel.textColor = .white
captionLabel.font = UIFont.systemFont(ofSize: 14)
captionLabel.textAlignment = .center
captionLabel.backgroundColor = UIColor.black.withAlphaComponent(0.5)
// 이미지 뷰의 하위 뷰로 캡션을 추가합니다.
captionLabel.translatesAutoresizingMaskIntoConstraints = false
imageView.addSubview(captionLabel)
NSLayoutConstraint.activate([
captionLabel.leadingAnchor.constraint(equalTo: imageView.leadingAnchor),
captionLabel.trailingAnchor.constraint(equalTo: imageView.trailingAnchor),
captionLabel.bottomAnchor.constraint(equalTo: imageView.bottomAnchor),
captionLabel.heightAnchor.constraint(equalToConstant: 40)
])
}
}
위의 코드에서 imageView
는 이미지가 표시될 UIImageView
입니다. imageUrl
은 이미지의 URL입니다. SDWebImage를 사용하여 이미지를 다운로드하고, 다운로드가 완료될 때 이미지 뷰의 하위 뷰로 캡션을 추가합니다.
참고 자료: