UIAlertAction按钮文本左对齐

Ash*_*shu 3 ios swift uialertcontroller uialertaction

我想将UIAlertAction文本对齐方式对齐到“左”并添加图标,如图所示。我在Google上花费了大量时间来获取解决方案,但找不到正确的答案。每个正文都发布警报标题,而不是警报操作标题。 在此处输入图片说明

请建议我要以正确的方式迅速

谢谢!!

小智 12

您可以使用下面的示例代码来做到这一点。简单而简单。

斯威夫特4

let actionSheetAlertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionSheetAlertController.addAction(cancelActionButton)


let documentsActionButton = UIAlertAction(title: "Documents", style: .default, handler: nil)
actionSheetAlertController.addAction(documentsActionButton)
documentsActionButton.setValue(#imageLiteral(resourceName: "doccument"), forKey: "image")
documentsActionButton.setValue(kCAAlignmentLeft, forKey: "titleTextAlignment")

let cameraActionButton = UIAlertAction(title: "Camera", style: .default, handler: nil)
actionSheetAlertController.addAction(cameraActionButton)
cameraActionButton.setValue(#imageLiteral(resourceName: "camera"), forKey: "image")
cameraActionButton.setValue(kCAAlignmentLeft, forKey: "titleTextAlignment")

let galleryActionButton = UIAlertAction(title: "Gallery", style: .default, handler: nil)
actionSheetAlertController.addAction(galleryActionButton)
galleryActionButton.setValue(#imageLiteral(resourceName: "gallery"), forKey: "image")
galleryActionButton.setValue(kCAAlignmentLeft, forKey: "titleTextAlignment")

actionSheetAlertController.view.tintColor = kTHEME_COLOR
self.present(actionSheetAlertController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)


jca*_*276 11

swift 5.0 的更新版本kCAAlignmentLeft(如@Niraj Solanki在此处回答)是CATextLayerAlignmentMode.left 因此代码应如下所示:

斯威夫特 5.0

documentsActionButton.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment")
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以用下面的示例代码来做到这一点。用您的图像替换图像名称

斯威夫特 3

 let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
 let camera = UIAlertAction(title: "Camera", style: .default) { (action) in
  // Do something
 }
 let cameraImage = UIImage(named: "icon_camera")
 camera.setValue(cameraImage, forKey: "image")
 camera.setValue(0, forKey: "titleTextAlignment")
 actionSheet.addAction(camera)
Run Code Online (Sandbox Code Playgroud)


kir*_*der 0

正如评论中已经说过的,UIAlertController 不提供其视图的自定义。但是,您可以构建自己的操作表视图或使用一些第三方,例如https://github.com/xmartlabs/XLActionController