2017-03-17 2 views
1

그래서 다양한 문자 길이를 포함하는 UITextView의 일부 블록으로 구성된 메시징 유형 앱을 만들고 있습니다. 이들은 거품 형 UIView에 있습니다. 일부 텍스트에 대해 UICollectionView 셀의 크기를 추정합니다.

let textView: UITextView = { 
    let text = UITextView() 
    text.text = "SAMPLE" 
    text.translatesAutoresizingMaskIntoConstraints = false 
    text.backgroundColor = .clear 
    text.textColor = .white 
    return text 
}() 
let bubbleView: UIView = { 
    let view = UIView() 
    view.backgroundColor = UIColor(r: 0, g: 137, b: 247) 
    view.layer.cornerRadius = 14 
    view.layer.masksToBounds = true 
    view.translatesAutoresizingMaskIntoConstraints = false 
    return view 
}() 
var bubbleWidthAnchor: NSLayoutConstraint? 

    bubbleView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true 
    bubbleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true 
    bubbleWidthAnchor = bubbleView.widthAnchor.constraint(equalToConstant: 250) 
    bubbleWidthAnchor?.isActive = true 
    bubbleView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true 

    textView.leftAnchor.constraint(equalTo: bubbleView.leftAnchor, constant: 8).isActive = true 
    textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true 
    textView.rightAnchor.constraint(equalTo: bubbleView.rightAnchor).isActive = true 
    textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true 

내가가 제대로 작동하지에 되어있는 사용자 정의 기능을 사용하고 셀의 높이를 설정합니다.

사용자 정의 기능 :

내가 UICollectionViewsizeForItemAt 함수 호출
private func estimatedFrameForText(text: String) -> CGRect { 
    let size = CGSize(width: 250, height: 250) 
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) 

    return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)], context: nil) 
} 

:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    var height: CGFloat = 80 //Arbitrary number 
    if let text = messages[indexPath.item].text { 
     height = estimatedFrameForText(text: text).height + 8 
    } 
    return CGSize(width: view.frame.width, height: height) 
} 

내가 ... 그것은 위대한 작동하지 않습니다되는 데 간단한 문제 : Example

어디서 잘못 될지 또는 필요한 예상 크기를 얻는 더 좋은 해결책 텍스트에 따라 셀?

답변

2

내가 알아챈 것은 문자 크기를 textView으로 설정하는 것이 었습니다.

attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16) 

그래서 당신은 동일하게 모두를 정의해야합니다 : 함수가 예상 크기를 가지고 얻을 수 있기 때문에 text.font = UIFont.systemFont(ofSize: 16)에서 퍼팅

이 필요했다.

관련 문제