如何绘制徽章,并将其添加到iOS Swift中的图像

w6lpcovy  于 2023-02-14  发布在  iOS
关注(0)|答案(1)|浏览(154)

我有通知图标,我想显示该图标与徽章,而新的通知可用,否则我需要只显示通知图标。
在我的情况下,我需要画一个红色的徽章,并将其添加到现有的图标图像上,然后将其传递给正在接受图像的其他自定义组件(自己的组件
请参考屏幕截图1-屏幕截图是通知图标,我有。
参考屏幕截图2预期一个当新的通知可用,我想提请徽章,并将其添加到现有的图标。

先谢了

2ledvvac

2ledvvac1#

AlertWithBadgeView是具有两个imageView的视图。alertImageView 用于背景图像,badgeImageView 用于标记图像。

class AlertWithBadgeView: UIView {
    
    var alertImageView: UIImageView!
    var badgeImageView: UIImageView!
    
    required init?(coder: NSCoder) {
        fatalError("don't use the view from within storyboards or xibs")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createView()
    }
    
    private func createView() {
        _ = {
            let imageView = UIImageView()
            addSubview(imageView)
            imageView.frame = bounds
            imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            alertImageView = imageView
        }()
        _ = {
            let imageView = UIImageView()
            addSubview(imageView)
            imageView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                imageView.widthAnchor.constraint(equalToConstant: 20),
                imageView.heightAnchor.constraint(equalToConstant: 20),
                imageView.topAnchor.constraint(equalTo: topAnchor),
                imageView.trailingAnchor.constraint(equalTo: trailingAnchor),
            ])
            badgeImageView = imageView
        }()
    }
}

基本的创建和配置可以通过 cellForRow(at:) 方法完成:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
    
    let alert = AlertWithBadgeView()
    alert.alertImageView.image = .init(systemName: "bell.badge")
    alert.badgeImageView.image = .init(systemName: "circle.fill")
    cell.addSubview(alert)
    alert.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        cell.centerYAnchor.constraint(equalTo: alert.centerYAnchor),
        cell.leadingAnchor.constraint(equalTo: alert.leadingAnchor, constant: -20),
        alert.widthAnchor.constraint(equalToConstant: 30),
        alert.heightAnchor.constraint(equalToConstant: 30),
    ])
    return cell
}

相关问题