UITTableView의 swift 샘플 코드에서 배우기

16640 단어 SwiftiOS
이 노트는 스와이프와 유키트에 대해 지식이 거의 없는 사람들이 쓴 학습 노트다.오류가 많을 수 있으니 주의하세요

UItableView의 종류

  • UItableView에는 두 가지가 있습니다.하나의 셀은 고정된 Static Cels이고 다른 셀의 수량은 가변적인 Dynamic Protoypes
  • 아래 캡처 오른쪽에 있는 Conntent는 탭의 밑에 있는 메뉴를 통해 유형을 변경할 수 있습니다

  • When you configure the attributes of a table view in the storyboard editor, you choose between two types of cell content: static cells or dynamic prototypes.
    Static cells. Use static cells to design a table with a fixed number of rows, each with its own layout. Use static cells when you know what the table looks like at design time, regardless of the specific information it displays.
    Dynamic prototypes. Use dynamic prototypes to design one cell and then use it as the template for other cells in the table. Use a dynamic prototype when multiple cells in a table should use the same layout to display information. Dynamic prototype content is managed by the data source at runtime, with an arbitrary number of cells.
    About Table Views in iOS Apps

    객체의 샘플 코드


    ViewController.swift
    import UIKit
    
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
        @IBOutlet weak var tableView: UITableView!
    
        var texts = ["one", "two", "three"];
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            tableView.delegate = self
            tableView.dataSource = self
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return texts.count
        }
    
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->  UITableViewCell {
            let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
            cell.textLabel?.text = texts[indexPath.row]
            return cell
        }
    }
    

    ViewController의 상속 클래스 설명

    import UIKit
    
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    

    UIViewController


    In an iOS app, you use a view controller (UIViewController) to manage a content view with its hierarchy of subviews.
    Each content view hierarchy that you build in your storyboard needs a corresponding view controller, responsible for managing the interface elements and performing tasks in response to user interaction.
    View controllers play many roles. They coordinate the flow of information between the app’s data model and the views that display that data, manage the life cycle of their content views, and handle orientation changes when the device is rotated. But perhaps their most obvious role is to respond to user input.

    UITableViewDelegate


    The delegate is responsible for dealing with user interactions, or customizing the display of certain entries.
    Cocoa and Cocoa Touch Define a Large Number of Protocols
    The delegate of a UITableView object must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.
    UITableViewDelegate - iOS Developer Library

    UITableViewDataSource


    The UITableViewDataSource protocol is adopted by an object that mediates the application’™s data model for a UITableView object. The data source provides the table-view object with the information it needs to construct and modify a table view.
    UITableViewDataSource Protocol Reference

    프로토콜과의 소통?


    In the real world, people on official business are often required to follow strict procedures when dealing with certain situations. Law enforcement officials, for example, are required to “follow protocol” when making enquiries or collecting evidence.
    In the world of object-oriented programming, it’s important to be able to define a set of behavior that is expected of an object in a given situation. As an example, a table view expects to be able to communicate with a data source object in order to find out what it is required to display. This means that the data source must respond to a specific set of messages that the table view might send.
    Working with Protocols - Programming with Objective-C, iOS Developer Library
    A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol doesn’t actually provide an implementation for any of these requirements—it only describes what an implementation will look like.
    Protocols

    Swift에서 Object-C로 정의된 protocol을 사용하는 방법


    In Swift, you can adopt protocols that are defined in Objective-C. Like Swift protocols, any Objective-C protocols go in a comma-separated list following the name of a class’s superclass, if any.
    SWIFT
    class MySwiftViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    //define the class
    }
    Objective-C protocols come in as Swift protocols. If you want to refer to the UITableViewDelegate protocol in Swift code, refer to it as UITableViewDelegate (as compared to id in Objective-C).
    Because the namespace of classes and protocols is unified in Swift, the NSObject protocol in Objective-C is remapped to NSObjectProtocol in Swift.
    Writing Swift Classes with Objective-C Behavior

    ViewController에 설치된 패키지


    func viewDidLoad()

  • UIViewController 메소드 재작성
  • ViewController 초기화 시 호출되는 방법
  • 샘플 코드에서tableView 구성원 변수 초기화
  • ViewController가 UItable ViewDelegate, UItable ViewDataSource를 계승하고 있기 때문에self를 설정하였으나 이 분류를 계승한 대상은 ViewController에 국한되지 않습니다
  •     override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            tableView.delegate = self
            tableView.dataSource = self
        }
    
    This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView method. You usually override this method to perform additional initialization on views that were loaded from nib files.
    UIViewController Class Reference

    func didReceiveMemoryWarning()

  • 메모리가 부족할 때 시스템에서 호출하는 방법
  • 호출될 때 필요하지 않은 자원을 방출하는 코드를 미리 쓴다
  • 이번 샘플 코드에는 특별히 해방할 수 있는 자원이 없기 때문에 특별히 쓴 것이 없다
  •     override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
    Sent to the view controller when the app receives a memory warning.
    UIViewController Class Reference

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

  • UItable View DataSource의Protocol로 실현하는 방법 요구
  • 지정된 구역의 row 수량을 반환값으로 되돌려줍니다
  •     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return texts.count
        }
    
    Tells the data source to return the number of rows in a given section of a table view.
    UITableViewDataSource Protocol Reference

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

  • UItable View DataSource의Protocol로 실현하는 방법 요구
  • 지정된 IndexPath에 대한 UItable ViewCell 인스턴스를 반환하는 방법
  •     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->  UITableViewCell {
            let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
            cell.textLabel?.text = texts[indexPath.row]
            return cell
        }
    

    이른바 NSIndexPath

  • section,row(모두Int형) 등 속성을 가진 클래스
  • The UIKit framework adds programming interfaces to the NSIndexPath class of the Foundation framework to facilitate the identification of rows and sections in UITableView objects and the identification of items and sections in UICollectionView objects.
    NSIndexPath

    UItableView를 조사할 때 참고할 만한 기사


    http://dev.classmethod.jp/smartphone/iphone/storyboard_uitableview/
    http://dev.classmethod.jp/smartphone/iphone/search_uitableview/
    http://dev.classmethod.jp/smartphone/iphone/uitableview_custom_cell/
    http://dev.classmethod.jp/smartphone/uitableview_navigationcontroller/
    http://blog.teamtreehouse.com/introduction-to-the-ios-uitableviewcontroller

    좋은 웹페이지 즐겨찾기