2017-10-15 9 views
0

나는 UITextView을 하위보기로 가지고 있으며 셀의 경계에 고정되어 있습니다.계산 UICollectionViewCell 높이 기본 돈 UITextView 특성화 된 텍스트

여기서 달성하고자하는 것은 UITextView attributedString을 기반으로하며 UITextView의 높이를 계산하여 스크롤 할 수 없도록 만들고 셀 높이에 해당 크기를 적용해야합니다.

여기서 문제는 NSAttributedString이 글꼴 크기가 다를 수 있으며 크기가 커지는 이미지가있을 수 있다는 것입니다.

여러 가지 내부 양식 (크기, 줄 바꿈, 이미지)을 가질 수있는 콘텐츠를 기준으로 크기를 계산하려면 어떻게해야합니까?

나는 다음과 같은 기능을 적용하는 데 사용하지만,이 경우 작동하지 않습니다

, 내부 컨텐츠 있기 때문에, 글꼴 크기를 연기 할 수처럼, 그것은 일정하지 :

private func estimatedHeightForText(_ text: String) -> CGFloat { 
    let approximateWidthOfBioTextView = view.frame.width - 24 // paddings 
    let size = CGSize(width: approximateWidthOfBioTextView, height: 1000) // height of 1000 is an arbitrary value 
    let attributes = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)] // attributes of the text 

    // gets the estimation height based on Text 
    let estimatedFrame = NSString(string: text).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) 
    return estimatedFrame.height 
} 

어떤 힌트?

대단히 감사합니다.

답변

1

다음은 간단한 ViewController 코드 일 수 있습니다.

enter image description here

것은 그냥 UITextView의 일부 더미 내용을로드하고 어디. UITableViewCell에있는 UITextView의 대표는이 후에 ViewController으로 설정됩니다.

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate { 

    @IBOutlet var tableView:UITableView! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 2 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cellId = "textCell" 
     let cell = tableView.dequeueReusableCell(withIdentifier: cellId)! 

     return cell 

    } 

    func textViewDidChange(_ textView: UITextView) { 
     tableView.beginUpdates() 
     tableView.endUpdates() 
    } 




} 

간단한 방법으로 자동 크기 조정을 수행하는 데 3 가지 핵심 사항이 있습니다.

1) UITextView의 경우 "Srolling Enabled"를 "NO"으로 설정하십시오. jQuery과 자동으로 치수 및 설정 일부 추정 높이를 (내가 엑스 코드 (9) 사용하고 있지만, 사용자가 설정할 수있는 설정

2) jQuery과 속성) enter image description here

또한 아래에 첨부 된 속성을 리사이징 자동 레이아웃을 확인할 수 있습니다 와 . 당신은 텍스트 뷰를 편집 할 때

enter image description here

3) 이제 대리인이 jQuery과를 업데이트하거나 beginUpdatesEndUpdates 사이에서 특정 indexPath를 다시로드 할 수 있습니다. func textViewDidChange(_ textView: UITextView)