자동 레이아웃 은 텍스트, 그림 에 따라 UITableView Cell 높이 를 자동 으로 계산 합 니 다.

6299 단어 UITableViewCell

원문 사이트 주소:http://lvwenhan.com/ios/449.html
 
이 시리즈 글 코드 창 고 는 https://github.com/johnlui/AutoLayout 에 있 습 니 다. 모 르 는 부분 이 있 으 면 제 Auto Layout 설정 을 참고 하 세 요. 로 컬 로 다운로드 하여 열 면 됩 니 다.
간단 한 소개
본 논문 에 서 는 UITableView Cell 의 높이 가 내부 의 UILabel 과 UIImageView 의 내용 에 따라 자동 으로 변 하도록 Auto Layout 기술 을 함께 사용 할 것 입 니 다.
인터페이스 구축
복구 하기 전에 삭 제 된 단추
단 추 를 누 르 면 firstTableView Controller 의 연결 을 복원 합 니 다:
구속 을 넣 어 중간 에 두 는 것 을 잊 지 마 세 요.
firstTableViewCell 수정
firstTableView Cell 의 사 이 즈 를 600 * 81 로 설정 하고 로고 의 사 이 즈 를 80 * 80 으로 설정 합 니 다.로고 의 제약 조건 을 다음 그림 과 같이 수정 합 니 다.
label 의 크기 와 위 치 를 수정 하고 다음 그림 과 같은 제약 조건 을 추가 합 니 다.
ViewController 에 UINavigationController 플러그 인 추가
돌아 오기 편 하도록.다음 그림 을 조작 합 니 다:
결과 보기
label 에 따라 firstTableView Cell 높이 를 자동 으로 계산 합 니 다.
label 을 선택 하면 lines 줄 수 를 0 으로 설정 합 니 다. 길이 제한 없 이 자동 으로 줄 을 접 습 니 다.
label 의 텍스트 내용 을 한 줄 이상 수정 합 니 다.
import UIKit



class firstTableViewController: UITableViewController {

    

    var labelArray = Array<String>() //      label     



    override func viewDidLoad() {

        super.viewDidLoad()



        var nib = UINib(nibName: "firstTableViewCell", bundle: nil)

        self.tableView.registerNib(nib, forCellReuseIdentifier: "firstTableViewCell")

        

        //      label     

        for i in 1...10 {

            var text = ""

            for j in 1...i {

                text += "Auto Layout"

            }

            labelArray.append(text)

        }

    }



    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }



    // MARK: - Table view data source



    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        return 50

    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1

    }



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

        return labelArray.count

    }



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

        let cell = tableView.dequeueReusableCellWithIdentifier("firstTableViewCell", forIndexPath: indexPath) as! firstTableViewCell



        cell.firstLabel.text = labelArray[indexPath.row]



        return cell

    }

}


이제 가장 중요 한 때 가 되 었 습 니 다. UITableView Cell 을 구동 하여 라벨 내용 에 적응 합 니 다.
1. height ForRowAtIndexPath 대신 estimated HeightForRowAtIndexPath 사용
estimated Height ForRow AtIndexPath 는 iOS 7 에서 출시 한 새로운 API 다.목록 줄 수가 만 줄 이면 height ForRow AtIndexPath 는 목록 이 표시 되 기 전에 만 번 을 계산 하고, estimated Height ForRow AtIndexPath 는 현재 화면 에 표 시 된 몇 줄 만 계산 하여 데이터 양 이 많 을 때의 성능 을 크게 향상 시 킬 수 있 습 니 다.
2. prototype Cell 구성원 변 수 를 새로 만 들 고 view DidLoad 에서 초기 화 합 니 다.
class firstTableViewController: UITableViewController {

    

    var labelArray = Array<String>() //      label     

    

    var prototypeCell: firstTableViewCell!



    override func viewDidLoad() {

        super.viewDidLoad()



        var nib = UINib(nibName: "firstTableViewCell", bundle: nil)

        self.tableView.registerNib(nib, forCellReuseIdentifier: "firstTableViewCell")

        

        //     prototypeCell     

        prototypeCell = tableView.dequeueReusableCellWithIdentifier("firstTableViewCell") as! firstTableViewCell

        

......


3. 높이 계산 하기
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    let cell = prototypeCell

    cell.firstLabel.text = labelArray[indexPath.row]

    return cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 1

}


4. 효과 보기
슈퍼 구덩이
위 에서 firstTableView Cell 이 label 에 따라 자동 으로 높이 를 계산 하 는 과정 에서 큰 구멍 이 있 습 니 다. 왼쪽 UIImageView 에 부 여 된 그림 이 비교적 크 면 다음 과 같은 이상 한 결 과 를 볼 수 있 습 니 다.
그림 이 UITable View Cell 을 크게 늘 렸 기 때 문 이지 우리 의 계산 이 효과 가 없 는 것 은 아니다.
큰 구덩이 해결: 공격 은 최선 의 수비!그림 에 따라 firstTableView Cell 높이 를 자동 으로 계산 합 니 다.
우선, 그림 의 렌 더 링 모드 를 Aspect Fit 으로 바 꿉 니 다.
Images. xcassets 에 그림 세 장 을 추가 하고 0, 1, 2 라 고 명명 하 며 크기 는 작은 것 부터 큰 것 까지 입 니 다.
cell ForRow AtIndexPath 에 코드 추가:
if indexPath.row < 3 {

    cell.logoImageView.image = UIImage(named: indexPath.row.description)

}


보기 효과:
앞의 두 셀 은 비교적 정상 적 으로 보 였 는데, 세 번 째 셀 은 왜 그렇게 많은 공백 이 생 겼 습 니까?이것 이 바로 Auto Layout 를 사용 하여 그림 의 폭 을 80px 로 제한 하 는 원생 문제 입 니 다. 폭 은 제한 되 었 지만 높이 는 여전히 원 그림 의 높이 입 니 다.
해결 방법 도 간단 하 다. 그림 의 너비 가 80px 보다 크 면 80px 너비 의 그림 을 다시 그 려 서 채 워 라.
Extensions 라 는 Group (가상 폴 더) 을 새로 만 들 고 그 내부 에 UIImage. swift 파일 을 새로 만 듭 니 다. 내용 은 다음 과 같 습 니 다.
import UIKit



extension UIImage {

    func resizeToSize(size: CGSize) -> UIImage {

        UIGraphicsBeginImageContext(size)

        self.drawInRect(CGRectMake(0, 0, size.width, size.height))

        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        

        return newImage

    }

}


UIImage 클래스 에 resizeToSize 라 는 방법 을 확장 하여 원 하 는 크기 로 다시 그린 UIImage 대상 을 되 돌려 줍 니 다.cellforRow AtIndexPath 의 코드 를 다음 과 같이 수정 합 니 다.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("firstTableViewCell", forIndexPath: indexPath) as! firstTableViewCell



    cell.firstLabel.text = labelArray[indexPath.row]

    

    var image = UIImage(named: (indexPath.row % 3).description)!

    if image.size.width > 80 {

        image = image.resizeToSize(CGSizeMake(80, image.size.height * (80 / image.size.width)))

    }

    cell.logoImageView.image = image



    return cell

}


해결!
효과 보기
위의 그림 에서 알 수 있 듯 이 cell 은 그림 과 문자 중 비교적 높 은 것 에 따라 완전히 적응 할 수 있다.
 

좋은 웹페이지 즐겨찾기