参见英文答案 >
How can I both stroke and fill with NSAttributedString w/ UILabel4个
我正在尝试创建一个meme生成器应用程序,以更好地理解Swift,Xdode,代理和UIKit.我试图使用NSAttributedStringKey将meme文本的颜色设置为白色并使用黑色笔划.黑色笔划正在工作,但当用户从相机胶卷中选择图像时,不会应用前景色.我已经搜索了StackOverflow,但所有的解决方案都适用于Swift 3,而不是Swift 4.我哪里出错?
我正在尝试创建一个meme生成器应用程序,以更好地理解Swift,Xdode,代理和UIKit.我试图使用NSAttributedStringKey将meme文本的颜色设置为白色并使用黑色笔划.黑色笔划正在工作,但当用户从相机胶卷中选择图像时,不会应用前景色.我已经搜索了StackOverflow,但所有的解决方案都适用于Swift 3,而不是Swift 4.我哪里出错?
我在下面列出了我的源代码.
import UIKit class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @IBOutlet weak var imagePickerView: UIImageView! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var topText: UITextField! @IBOutlet weak var bottomText: UITextField! let memeTextAttributes:[String:Any] = [ NSAttributedStringKey.strokeColor.rawValue: UIColor.black,NSAttributedStringKey.foregroundColor.rawValue: UIColor.white,NSAttributedStringKey.font.rawValue: UIFont(name: "HelveticaNeue-CondensedBlack",size: 40)!,NSAttributedStringKey.strokeWidth.rawValue: 3.0] override func viewDidLoad() { super.viewDidLoad() // Diable camer a button if camera ource isn't available cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) topText.defaultTextAttributes = memeTextAttributes bottomText.defaultTextAttributes = memeTextAttributes } // MARK: Delegate Methods func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { imagePickerView.image = image self.dismiss(animated: true,completion: nil) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.dismiss(animated: true,completion: nil) } @IBAction func pickAnImageFromAlbum(_ sender: Any) { let pickerController = UIImagePickerController() pickerController.delegate = self pickerController.sourceType = .photoLibrary present(pickerController,animated: true,completion: nil) } @IBAction func pickAnImageFromCamera(_ sender: Any) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = .camera present(imagePicker,completion: nil) } }
解决方法
如果您也设置foregroundColor,请使用负strokeWidth.否则,只能看到中风.
let attributes = [ NSAttributedStringKey.strokeColor.rawValue: UIColor.black,NSAttributedStringKey.backgroundColor.rawValue: UIColor.red,NSAttributedStringKey.strokeWidth.rawValue: -4.5]
编辑:请参阅rmaddy关于为什么我们在下面的情况下需要rawValue的评论.