我需要在UITableView中显示与其姓名相对应的每个用户的个人资料照片.在下载图像之前,我需要在GMail应用程序中显示带有他名字的第一个字母的图像.如何在Swift for iOS中以编程方式执行此操作?
"不需要任何框架"
"它的工作非常棒"
@IBOutlet weak var IBtxtFieldName:UITextField! @IBOutlet weak var IBtxtFieldSurname:UITextField! @IBOutlet weak var IBImgViewUserProfile:UIImageView! @IBAction func IBbtnShowTapped(sender: UIButton) { let lblNameInitialize = UILabel() lblNameInitialize.frame.size = CGSize(width: 100.0, height: 100.0) lblNameInitialize.textColor = UIColor.whiteColor() lblNameInitialize.text = String(IBtxtFieldName.text!.characters.first!) + String(IBtxtFieldSurname.text!.characters.first!) lblNameInitialize.textAlignment = NSTextAlignment.Center lblNameInitialize.backgroundColor = UIColor.blackColor() lblNameInitialize.layer.cornerRadius = 50.0 UIGraphicsBeginImageContext(lblNameInitialize.frame.size) lblNameInitialize.layer.renderInContext(UIGraphicsGetCurrentContext()!) IBImgViewUserProfile.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() }
"SWIFT 3.0"
@IBAction func IBbtnShowTapped(sender: UIButton) { let lblNameInitialize = UILabel() lblNameInitialize.frame.size = CGSize(width: 100.0, height: 100.0) lblNameInitialize.textColor = UIColor.white lblNameInitialize.text = String(IBtxtFieldName.text!.characters.first!) + String(IBtxtFieldSurname.text!.characters.first!) lblNameInitialize.textAlignment = NSTextAlignment.center lblNameInitialize.backgroundColor = UIColor.black lblNameInitialize.layer.cornerRadius = 50.0 UIGraphicsBeginImageContext(lblNameInitialize.frame.size) lblNameInitialize.layer.render(in: UIGraphicsGetCurrentContext()!) IBImgViewUserProfile.image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() }
这对于UIImageView来说是完美的:https://github.com/bachonk/UIImageView-Letters.基本上,它创建一个UIImage,在中心,输入的第一个和最后一个单词的首字母.背景颜色可以是随机的或分配的.
以下是此类别可以执行的操作的示例:
[编辑]
您可能还想查看这个:https://github.com/bofiaza/IPImage
使用FredLoh的建议:
我在故事板中创建了一个UILabel(nameInitialLabel).调整了它的尺寸和字体.
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() }
我从https://github.com/uttesh/ngletteravatar中提取了alphabetColors映射数组