ios - Swift - 自定义单元格内容(UILabel、UIImageView)
问题描述
我想定制我的UICollectionViewCell
,但它不能像我希望的那样工作。
这是我的第一个单元格的代码:
class MainWishlistCell: UICollectionViewCell {
let wishlistImage: UIImageView = {
let v = UIImageView()
v.translatesAutoresizingMaskIntoConstraints = false
v.image = UIImage(named: "logoGroß")
v.layer.cornerRadius = 3.0
v.layer.shadowColor = UIColor.black.cgColor
v.layer.shadowOffset = CGSize(width: 3, height: 3)
v.layer.masksToBounds = false
return v
}()
let wishlistLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.text = "Main Wishlist"
v.font = UIFont(name: "Avenir Next-Bold", size: 18)
v.textColor = .darkGray
v.textAlignment = .center
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
contentView.addSubview(wishlistImage)
contentView.addSubview(wishlistLabel)
// constrain view to all 4 sides
NSLayoutConstraint.activate([
wishlistImage.topAnchor.constraint(equalTo: contentView.topAnchor),
wishlistImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
wishlistImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
wishlistImage.heightAnchor.constraint(equalToConstant:150),
wishlistLabel.topAnchor.constraint(equalTo: wishlistImage.bottomAnchor,constant: 1),
wishlistLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
wishlistLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
wishlistLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
])
}
}
它看起来像这样:
1. 问题- 为什么标签不是bold
?
2. 问题- 为什么没有cornerRadius
?
3. 问题- 为什么不shadow
出现(底部+右侧)?
解决方案
试试这个
- 问题:1
v.font = UIFont(name: "AvenirNext-Bold", size: 18)
//删除Avenir和Next之间的空格
- 问题:2 & 3
将此扩展添加到您的项目中
extension UIImageView {
func addShadow(offset: CGSize, color: UIColor, radius: CGFloat, opacity: Float)
{
layer.masksToBounds = false
layer.shadowOffset = offset
layer.shadowColor = color.cgColor
layer.shadowRadius = radius
layer.shadowOpacity = opacity
}
}
并称之为
let wishlistImage: UIImageView = {
let v = UIImageView()
v.translatesAutoresizingMaskIntoConstraints = false
v.image = UIImage(named: "logoGroß")
v.layer.cornerRadius = 3.0
v.addShadow(offset: CGSize(width: 3, height: 3), color: UIColor.black, radius: 2.0, opacity: 1.0)
return v
}()
推荐阅读
- google-apps-script - 有没有办法在 iframe 以外的网页中嵌入(执行)谷歌应用脚本?
- rest - HTTP GET 上的部分对象
- html - 需要在css中删除一些空间
- python - 如何将熊猫数据透视表转换为常规数据框
- pine-script - 不能使用可变变量作为安全函数的参数?
- .net-core - dotnet core 2.2 布局页面和组件
- swift - PageView (UIPageViewController) 的条件同级中断分页
- php - 如何正确处理 PHP 异常
- reactjs - 反应,添加项目时从 api 重新获取
- constructor - 通过按钮单击导航到页面时未调用 ngOnInit,但在浏览器中直接导航到该页面时调用