2016-05-31 6 views
1

UIImageView가 주어진 그림에 따라 높이를 동적으로 변경하려고합니다. UIImageView는 사용자 정의 셀 내부에 있습니다.Autolayout을 사용하여 TableView 셀에서 UIImageView를 자동 크기 조정

다음은 제약 조건은 다음과 같습니다

  1. 다른 가장자리 화면의 가장자리에서 걸쳐해야합니다.
  2. 높이가 동적이어야하며 프레임의 너비를 초과하지 않아야합니다. 의 높이를 변경하는

    enter image description here

    내가 (postHeight으로 함) 코드에서 높이 제약 조건을 사용

지금까지 내가 인터페이스 빌더를 사용하여있는 UIImageView에 다음과 같은 제약 조건을 추가했습니다 UIImageView에 아래와 같이

import UIKit 

class ImageTableViewCell: UITableViewCell { 

    @IBOutlet weak var postImage: UIImageView! 
    @IBOutlet weak var postHeight: NSLayoutConstraint! 

    var post:UIImage! = nil { 
     didSet { 
      let x = post.size.width 
      let y = post.size.height 
      var newHeight = (y/x) * self.frame.width 
      newHeight = newHeight > self.frame.width ? self.frame.width : newHeight 
      postHeight.constant = newHeight 
      postImage.contentMode = .ScaleAspectFit 
      postImage.image = post 
     } 
    } 

    override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 
    } 

    override func setSelected(selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 

     // Configure the view for the selected state 
    } 

} 

실행, 콘솔은 몇 가지 제약 조건을 만족시킬 수 없음을 보여줍니다. 그리고 출력 :

TryImageView[89952:2477907] Unable to simultaneously satisfy constraints. 
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
     (1) look at each constraint and try to figure out which you don't expect; 
     (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x7aef8560 V:[UIImageView:0x7aef96b0(291.355)]>", 
    "<NSLayoutConstraint:0x7aef9b30 UIImageView:0x7aef96b0.top == UITableViewCellContentView:0x7aef9340.topMargin - 8>", 
    "<NSLayoutConstraint:0x7aef9b90 UITableViewCellContentView:0x7aef9340.bottomMargin == UIImageView:0x7aef96b0.bottom - 8.5>", 
    "<NSLayoutConstraint:0x7ae5e990 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7aef9340(291)]>" 
) 

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7aef8560 V:[UIImageView:0x7aef96b0(291.355)]> 

테이블 뷰는 셀의 크기를 조정해야하기 때문에 viewDidLoad()에도이 속성이 있습니다.

override func viewDidLoad() { 
     super.viewDidLoad() 
     self.tableView.estimatedRowHeight = 90 
     self.tableView.rowHeight = UITableViewAutomaticDimension 
} 

제 제한이 작동하지 않는 이유는 무엇입니까?

  • 오른쪽, 왼쪽 및 하단, 상단에 연결된
  • 고정 높이

높이 제약 조건을 제거 감사

답변

0

당신은 귀하의 이미지 뷰에 대한 제약 조건을 설정합니다. 셀 높이가 50이라고 가정합니다. 이미지보기의 높이를 고정시킬 수 없습니다. 그것이 전체 세포를 커버한다면 높이도 50이 될 것입니다. 이미지의 높이를 찾아서 배열에 넣어야합니다.

var heights = [CGFloat]() 

당신은 당신의 높이를 찾을 때 :

heights = [50, 60, 70] 

는 그 다음 heightForRowAtIndexPath 방법이 높이를 돌려줍니다.

이미지보기의 contentMode도 설정해야합니다.

imageView.contentMode = .ScaleAspectFit