Categories: iOS

[iOS] MessageKitでAvatarViewの上にラベルを表示する

なかなか苦戦したのでめも。

むりやりUILabelを追加して表示してる。
masksToBounds = falseにしてるので丸く映らなくなる副作用あり。

func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
    let avatar = Avatar(image: ownerIcon(roomDocumentId: roomDocumentId, userId: userId), initials: initial)
    avatarView.set(avatar: avatar)
    let number = String(describing: indexPath.section + 1)
    if let abobeLabel = viewWithTag(AvatarView.labelTag) as? UILabel {
        abobeLabel.text = number
        return
    }
    let abobeLabel = UILabel(frame: CGRect(x: 0, y: -10, width: frame.width, height: 14))
    abobeLabel.textAlignment = .center
    abobeLabel.text = number
    abobeLabel.font = UIFont.systemFont(ofSize: 11)
    abobeLabel.tag = AvatarView.labelTag
    addSubview(abobeLabel)
    // これをやらないと丸くきりとられているため、ラベルが表示されない
    layer.masksToBounds = false
}

extension AvatarView {
    static let labelTag = 10
}

だれかいい方法あったら教えてください。

mogmet

View Comments

  • Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

  • Thanks for sharing. I read many of your blog posts, cool, your blog is very good.