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

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

Auto Layout เป็นระบบ Layout แบบ Constraint-based สำหรับพัฒนา UI บน iOS เป็น Adaptive UI ที่ปรับตัวตามขนาดหน้าจอและทิศทางต่างๆ

Auto Layout ขึ้นอยู่กับ Constraints ที่นักพัฒนากำหนดความสัมพันธ์ระหว่าง Element เพื่อกำหนดตำแหน่ง

ทำไมต้องใช้ Auto Layout?

UI ต้องเข้ากันได้กับทุกขนาดหน้าจอและทิศทาง Auto Layout ช่วยแก้ปัญหานี้

ตัวอย่าง: ปุ่มกึ่งกลางบน iPhone 6 ไม่ได้อยู่กึ่งกลางบนอุปกรณ์อื่น เพราะขนาดต่างกัน

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

เริ่มต้นใช้งาน

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

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

ขั้นตอนที่ 2: เพิ่มปุ่มใน Storyboard

เลือก Device เป็น iPhone 7 Plus เพิ่มปุ่มโดยไม่ตั้ง Constraints

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

เข้าใจ Layout Buttons

Xcode มี 2 วิธีสร้าง Constraints: Auto Layout Bar และ Control-drag ที่มุมขวาล่างของ Interface Builder มีปุ่ม 5 ปุ่มสำหรับ Constraints

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

ทฤษฎีพื้นฐาน: 4 พารามิเตอร์ (Leading, Trailing, Top, Bottom) รวมถึง Width, Height, Vertical/Horizontal Centers

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

ขั้นตอนที่ 3: จัดกึ่งกลางด้วย Align

คลิกปุ่ม → Tab Align → เปิด Horizontally และ Vertically in Container

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

ปุ่มจะอยู่กึ่งกลาง:

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

หรือใช้ Control-drag: กด Control ลากจากปุ่มไป Container เลือก Center Horizontally/Vertically

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

ขั้นตอนที่ 4: กำหนด Width และ Height

กด Add New Constraints → ตั้ง Height และ Width

การใช้งาน Xcode Auto Layout ใน Swift และ iOS

ทางเลือก: ใช้ Leading, Trailing, Top, Bottom แทน Center ก็ได้

ขั้นตอนที่ 5: ทดสอบบนอุปกรณ์ต่างๆ

รันบนอุปกรณ์และทิศทางต่างๆ

การใช้งาน Xcode Auto Layout ใน Swift และ iOS
การใช้งาน Xcode Auto Layout ใน Swift และ iOS

แก้ไข Constraints

ใน Utility Pane (ขวา) เลือกไอคอนรูปไม้บรรทัด (ตัวที่ 5) เลื่อนลงเพื่อแก้ไข/ลบ Constraints

การใช้งาน Xcode Auto Layout ใน Swift และ iOS