Make images with name initials like Gmail in Swift programmatically for iOS

后端 未结 8 2229
孤城傲影
孤城傲影 2021-02-05 18:03

I need to display a profile pic of every user corresponding to his name in a UITableView. Until the image is downloaded I need to show an image with his name\'s first alphabet l

8条回答
  •  时光取名叫无心
    2021-02-05 18:32

    Using FredLoh's suggestion :

    I made a UILabel(nameInitialLabel) in the storyboard. Adjusted it's dimensions and font.

    func setDefaultImage(name: String) {
        nameInitialLabel.text = String(name[name.startIndex])
        nameInitialLabel.backgroundColor = pickColor(name[name.startIndex])
        nameInitialLabel.enabled = true
    }
    
    func pickColor(alphabet: Character) -> UIColor {
        let alphabetColors = [0x5A8770, 0xB2B7BB, 0x6FA9AB, 0xF5AF29, 0x0088B9, 0xF18636, 0xD93A37, 0xA6B12E, 0x5C9BBC, 0xF5888D, 0x9A89B5, 0x407887, 0x9A89B5, 0x5A8770, 0xD33F33, 0xA2B01F, 0xF0B126, 0x0087BF, 0xF18636, 0x0087BF, 0xB2B7BB, 0x72ACAE, 0x9C8AB4, 0x5A8770, 0xEEB424, 0x407887]
        let str = String(alphabet).unicodeScalars
        let unicode = Int(str[str.startIndex].value)
        if 65...90 ~= unicode {
            let hex = alphabetColors[unicode - 65]
            return UIColor(red: CGFloat(Double((hex >> 16) & 0xFF)) / 255.0, green: CGFloat(Double((hex >> 8) & 0xFF)) / 255.0, blue: CGFloat(Double((hex >> 0) & 0xFF)) / 255.0, alpha: 1.0)
        }
        return UIColor.blackColor()
    }
    

    I've extracted the alphabetColors mapping array from https://github.com/uttesh/ngletteravatar

提交回复
热议问题