Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีควบคุม Width และ Height ของ Default Alert Dialog ใน iOS

บางครั้งต้องปรับขนาด Alert ใช้ NSLayoutConstraint อ่านรายละเอียด

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → New Project → Single View Application → ชื่อ "changeheightandwidth"

ขั้นตอนที่ 2: สร้างปุ่มและ IBAction

Main.storyboard: ปุ่ม "Tap" @IBAction ชื่อ btnATap

ขั้นตอนที่ 3: โค้ดปรับขนาด Alert

let alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: .alert)

Height Constraint:

let constraintHeight = NSLayoutConstraint(
item: alert.view!, attribute: .height, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
alert.view.addConstraint(constraintHeight)

Width Constraint:

let constraintWidth = NSLayoutConstraint(
item: alert.view!, attribute: .width, relatedBy: .equal,
toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300)
alert.view.addConstraint(constraintWidth)

เพิ่ม Action และ Present:

let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
let OKAY = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(OKAY)
self.present(alert, animated: true, completion: nil)

โค้ดเต็มใน IBAction

@IBAction func btnATap(_ sender: Any) {
let alert = UIAlertController(title: "Your Title", message: "Your Message", preferredStyle: .alert)
let constraintHeight = NSLayoutConstraint(item: alert.view!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
alert.view.addConstraint(constraintHeight)
let constraintWidth = NSLayoutConstraint(item: alert.view!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300)
alert.view.addConstraint(constraintWidth)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
let OKAY = UIAlertAction(title: "Done", style: .default, handler: nil)
alert.addAction(OKAY)
self.present(alert, animated: true, completion: nil)
}

วิธีควบคุม Width และ Height ของ Default Alert Dialog ใน iOS