2017-05-03 2 views
0

저는 UIStoryBoard에서 numberOFLines가 6으로 설정된 3 개의 UILabels가있는 신속한 3.0 프로젝트에서 작업하고 있습니다. 레이블 아래에 "더보기"옵션으로 기능하는 세 개의 UIButton이 있습니다. 때로는 내 코드가 잘 작동합니다. 레이블을 자르면 더 많은 버튼을보고 한 번 클릭하면 전체 내용이 표시되는 반면, UILabel 내용은 자르지 만 "더 자세히"버튼이 표시되지 않습니다. 전체 내용을 볼 수 없습니다. 코드에서 누락 된 부분은 도움이 될 것입니다.instrictContentSize on UILabel 다른 인스턴스에서 다른 값을 반환합니다.

import UIKit 

class MP3ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { 

    @IBOutlet var descriptionSeeMoreBtn: UIButton! 

    @IBOutlet var howToUseSeeMoreBtn: UIButton! 

    @IBOutlet var cautionsSeeMreBtn: UIButton! 
    var seeMoreIsShowing = false 
    @IBOutlet var cautionsContentLbl: UILabel! 
    @IBOutlet var howToUseContentLbl: UILabel! 
    @IBOutlet var descriptionContentLbl: UILabel! 

    override func viewDidLoad() { 
     self.descriptionContentLbl.sizeToFit() 
     self.howToUseContentLbl.sizeToFit() 
     self.cautionsContentLbl.sizeToFit() 
     getItButton.layer.cornerRadius = 5 
     activityIndicator.startAnimating() 
     let mediaID = mediaDetails?["entity_key"] as! String 
     let url = URL(string: Config.MP3_LIST + "?mediaId=\(mediaID)") 
     let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in 

      if(error != nil){ 
       print(error!); 
       DispatchQueue.main.sync(execute: { 
        self.activityIndicator.stopAnimating() 
       }) 
      } 
      else{ 
       do{ 
        if let urlContent = data { 
         let serverResponseData = try (JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary 
         if(serverResponseData["error"] == nil){ 
          self.mediaDetails = serverResponseData 
          print("Media :",self.mediaDetails!) 
          self.mediaList = (self.mediaDetails?["trackList"]as? NSArray)! 

          DispatchQueue.main.sync(execute: { 

           self.descriptionContentLbl.text = self.mediaDetails?["description"] as? String ?? "description...." 
           self.howToUseContentLbl.text = self.mediaDetails?["howToUse"] as? String ?? "How to use......." 
           self.cautionsContentLbl.text = self.mediaDetails?["cautions"] as? String ?? "cautions...." 
           let track = ((self.mediaDetails?["trackList"] as! NSArray)[0]) as! NSDictionary 
           self.activityIndicator.stopAnimating() 
          }) 
         } 
        } 
       } 
       catch { 
        print("Error In Json De-serialization") 
       } 
       DispatchQueue.main.sync(execute: { 
        self.activityIndicator.stopAnimating() 
       }) 
      } 
     }) 
     task.resume(); 

    } 

    override func viewDidAppear(_ animated: Bool) { 
     loadTheInitialLabelText() 
     self.tableView.tableFooterView = UIView(frame: .zero) 
    } 

    @IBAction func descriptionSeeMoreButtonPressed(_ sender: Any) { 
     if (seeMoreIsShowing) { 
      self.descriptionContentLbl.numberOfLines = 6 
      self.descriptionSeeMoreBtn.setTitle("see more", for: .normal) 
     }else { 
      self.descriptionContentLbl.numberOfLines = 0 
      self.descriptionSeeMoreBtn.setTitle("show less", for: .normal) 
     } 
     seeMoreIsShowing = !seeMoreIsShowing 
    } 
    @IBAction func howToUSeSeeMoreButtonPressed(_ sender: Any) { 
     if (seeMoreIsShowing) { 
      self.howToUseContentLbl.numberOfLines = 6 
      self.howToUseSeeMoreBtn.setTitle("see more", for: .normal) 
     }else { 
      self.howToUseContentLbl.numberOfLines = 0 
      self.howToUseSeeMoreBtn.setTitle("show less", for: .normal) 
     } 
     seeMoreIsShowing = !seeMoreIsShowing 
    } 


    @IBAction func cautionsSeeMoreButtonPressed(_ sender: Any) { 
     if (seeMoreIsShowing) { 
      self.cautionsContentLbl.numberOfLines = 6 
      self.cautionsSeeMreBtn.setTitle("see more", for: .normal) 
     }else { 
      self.cautionsContentLbl.numberOfLines = 0 
      self.cautionsSeeMreBtn.setTitle("show less", for: .normal) 
     } 
     seeMoreIsShowing = !seeMoreIsShowing 
    } 

func loadTheInitialLabelText() { 
     let DescriptionTextheight = self.descriptionContentLbl.text?.height(withConstrainedWidth: self.descriptionContentLbl.frame.width, font: self.descriptionContentLbl.font) 
     if self.descriptionContentLbl.intrinsicContentSize.height < DescriptionTextheight! { 
      self.descriptionSeeMoreBtn.isHidden = false 
     }else{ 
      self.descriptionSeeMoreBtn.isHidden = true 
     } 

     let howToUseTextheight = self.howToUseContentLbl.text?.height(withConstrainedWidth: self.howToUseContentLbl.frame.width, font: self.howToUseContentLbl.font) 
     if self.howToUseContentLbl.intrinsicContentSize.height < howToUseTextheight! { 
      self.howToUseSeeMoreBtn.isHidden = false 
     }else{ 
      self.howToUseSeeMoreBtn.isHidden = true 
     } 

     let cautionsTextheight = self.cautionsContentLbl.text?.height(withConstrainedWidth: self.cautionsContentLbl.frame.width, font: self.cautionsContentLbl.font) 
     if self.cautionsContentLbl.intrinsicContentSize.height < cautionsTextheight! { 
      self.cautionsSeeMreBtn.isHidden = false 
     }else{ 
      self.cautionsSeeMreBtn.isHidden = true 
     } 

    } 

} 
extension String { 

    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { 
     let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) 
     let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) 

     return boundingBox.height 
    } 
} 

답변

1

크기 사용자 정의 텍스트 값을 설정하기 전에 레이블을 지정하고 크기 값을 설정 한 후에는 sizeToFit을 지정하십시오. 이것만으로는 문제를 해결할 수 없습니다.

나는 웹 서비스가 너무 오래 돌아오고 있습니다. 따라서 웹 서비스가 대기하는 동안 나머지 프로그램은 계속 실행됩니다.

그래서 빈 레이블을 비교하고 높이를 얻은 다음 해당 레이블의 본질적인 콘텐츠 크기를 가져옵니다. intrinsic 크기는 비 텍스트로 채워진 레이블의 크기이며, 함수가 해당 레이블에 대해 계산 한 높이보다 작습니다. 이것은 당신의 단추를 숨기기 끝낸다.

그런 다음 URLSession은 데이터를 제공하고 레이블의 텍스트 값을 설정하지만 높이 계산은 이미 발생했습니다.

레이블 텍스 트가 설정된 후 ViewDidLoad URLSession 핸들러에서 LoadInitialText()를 호출하면 쉽게 해결할 수 있습니다.

+0

귀하의 답변은 절대적으로 의미가 있으며, 제가 흐름을 이해할 수있게 해줍니다. 내가 시도 할 수있는 다른 것. 그러나 이것이 내 코드의 실행에 대한 정확한 그림을 제공하기 때문에 나는 이것을 추천해야만한다. – danu

+0

말하기는 어렵지만, seemoreisshowing 변수는 어디에도 설정되어 있지 않다. 그렇지 않으면 실제로 숨겨진 값을 설정하는 것을보기 위해 if 문에서 숨겨진 값과 높이 값을 디버깅해볼 수 있습니다. – Ganksy