Add multiple line text to UIAlertAction in correct size
Asked Answered
C

0

0

I'm showing the 2 text values in UIAlertAction.

I used the following code.

UILabel.appearance(whenContainedInInstancesOf: [UIAlertController.self]).numberOfLines = 0

let actionSheetController = UIAlertController(title: nil, message: "Call", preferredStyle: .actionSheet)
actionSheetController.view.tintColor = UIColor.red

for key in phoneNumbers.keys {
    let phoneNumber = phoneNumbers[key] ?? ""
    let actionTitle = "\(key)\n\(phoneNumber)"
    let phoneNumberAction = UIAlertAction(title: actionTitle, style: .default) { action -> Void in
        self.makeCall(phoneNumber)
    }
    actionSheetController.addAction(phoneNumberAction)

    let attributedText = NSMutableAttributedString(string: actionTitle)

    let range = NSRange(location: key.count, length: attributedText.length - key.count)
            attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.gray, range: range)

    guard let label = (phoneNumberAction.value(forKey: "__representer")as? NSObject)?.value(forKey: "label") as? UILabel else { return }
    label.attributedText = attributedText
}

let cancelAction = UIAlertAction(title: LOCALSTR("Cancel"), style: .cancel) { action -> Void in

}
actionSheetController.addAction(cancelAction)

present(actionSheetController, animated: true, completion: nil)

But the view size is not increased automatically and there is no enough space at the top and bottom.

enter image description here

How can I figure out this?

Cloudburst answered 14/4, 2020 at 20:15 Comment(2)
#25020201Kingofarms
For me __representer is always nil.Augend

© 2022 - 2024 — McMap. All rights reserved.