Как центрировать текстовое представление в tableViewCell? - PullRequest
0 голосов
/ 29 сентября 2018

У меня есть статический tableView, который я создаю так ...

 override func viewDidLoad() {
        super.viewDidLoad()

        usernameLabel.text = "Username"
        usernameDisplay.text = "placeholder"
        usernameDisplay.textColor = self.view.tintColor
        usernameLabel.frame = CGRect(x: self.view.bounds.minX, y: self.usernameCell.bounds.minY, width: self.view.frame.width, height: self.usernameCell.bounds.height)
        usernameDisplay.frame = CGRect(x: self.usernameCell.bounds.minX, y: self.usernameCell.bounds.minY, width: self.view.frame.width, height: self.usernameCell.bounds.height)
        usernameDisplay.textAlignment = .right
        usernameCell.addSubview(usernameLabel)
        usernameCell.addSubview(usernameDisplay)

        membershipTierLabel.text = "Membership Status"
        membershipTierDisplay.text = "Free (0-1GB)"
        membershipTierDisplay.textColor = self.view.tintColor
        membershipTierLabel.frame = CGRect(x: self.view.bounds.minX, y: self.membershipTierCell.bounds.minY, width: self.view.frame.width, height: self.membershipTierCell.bounds.height)
        membershipTierDisplay.frame = CGRect(x: self.view.bounds.minX, y: self.membershipTierCell.bounds.minY, width: self.view.frame.width, height: self.membershipTierCell.bounds.height)
        membershipTierDisplay.textAlignment = .right
        membershipTierCell.addSubview(membershipTierLabel)
        membershipTierCell.addSubview(membershipTierDisplay)

        dataUsedLabel.text = "Data Used"
        dataUsedDisplay.text = String(UserDefaults.standard.integer(forKey: "total_storage"))
        dataUsedDisplay.textColor = self.view.tintColor
        dataUsedLabel.frame = CGRect(x: self.view.bounds.minX, y: self.dataUsedCell.bounds.minY, width: self.view.frame.width, height: self.dataUsedCell.bounds.height)
        dataUsedDisplay.frame = CGRect(x: self.view.bounds.minX, y: self.membershipTierCell.bounds.minY, width: self.view.frame.width, height: self.membershipTierCell.bounds.height)
        dataUsedDisplay.textAlignment = .right
        dataUsedCell.addSubview(dataUsedLabel)
        dataUsedCell.addSubview(dataUsedDisplay)

        tipsText.text = "You can change the color of a progression tag by long-pressing it on the Progressions homepage"

        tipsText.frame = CGRect(x: tipsCell.bounds.minX,y: self.tipsCell.bounds.minY,width: tipsCell.bounds.width,height:self.tipsCell.bounds.height)
        //tipsText.textColor = UIColor.white
        //tipsText.textAlignment = .center
        tipsText.backgroundColor = self.view.tintColor
        tipsText.font = tipsText.font?.withSize(15)
        tipsText.autoresizingMask = [.flexibleWidth, .flexibleHeight]

//        tipsText.centerYAnchor.constraint(equalTo: tipsCell.centerYAnchor, constant:0).isActive = true
//        tipsText.centerXAnchor.constraint(equalTo: tipsCell.centerXAnchor, constant:0).isActive = true
        //tipsText.textContainerInset = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
        tipsCell.backgroundColor = self.view.tintColor
        tipsCell.addSubview(tipsText)
        tipsText.center = CGPoint(x: tipsCell.bounds.midX, y: tipsCell.bounds.midY)

        feedbackText.text = "Feedback is loved! Please email with any issues, comments, ideas, or concerns"
        feedbackText.frame = CGRect(x: self.feedbackCell.bounds.minX,y: self.feedbackCell.bounds.minY,width: self.feedbackCell.bounds.width,height:self.feedbackCell.bounds.height)
        feedbackText.font = feedbackText.font?.withSize(15)
        feedbackCell.addSubview(feedbackText)

        //let bytes = UserDefaults.standard.integer(forKey: "total_storage")
        //storageAmount.text = format(bytes:Double(bytes))
        // Do any additional setup after loading the view.
        //myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
        myTableView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
        myTableView.dataSource = self
        myTableView.delegate = self
        self.view.addSubview(myTableView)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section != 0 {
            return 100
        } else {
            return UITableViewAutomaticDimension
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch(section) {
        case 0: return 3    // section 0 has 2 rows
        case 1: return 1
        case 2: return 1// section 1 has 1 row
        default: fatalError("Unknown number of sections")
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch(indexPath.section) {
        case 0:
            switch(indexPath.row){
            case 0:
                print("username")
                return self.usernameCell
            case 1:
                return self.membershipTierCell
            case 2:
                return self.dataUsedCell
            default: fatalError("Unknown row")
            }
        case 1:
            switch(indexPath.row){
            case 0:
                return self.tipsCell
            default: fatalError("Unknown row")
            }
        case 2:
            print("feedback")
            switch(indexPath.row){
            case 0:
                print("feedback")
                return self.feedbackCell
            default: fatalError("Unknown row")
            }
        default: fatalError("Unknown section")
        }
    }
}

Прямо сейчас это выглядит как enter image description here

Как вы можетевидите, я пытаюсь установить tipsText (UITextView) в точном центре tipsCell, используя: tipsText.center = CGPoint(x: tipsCell.bounds.midX, y: tipsCell.bounds.midY)

Как вы можете видеть, это не работает, так как tipsText все еще находится в верхней части tipsCell,Как я могу центрировать это, как я хочу здесь?

Ответы [ 2 ]

0 голосов
/ 29 сентября 2018

Я думаю, что у вас есть два способа выполнить ваше желание.

Один из способов - установить высоты для tipsCell и feedBackCell равными 100 в IB, если у вас есть.

Другой способ - добавить коды следующим образом:

 tipsText.textAlignment = .center
    tipsText.numberOfLines = 0
    tipsText.autoresizingMask = [.flexibleWidth, .flexibleHeight]

  feedbackText.textAlignment = .center
   feedbackText.numberOfLines = 0
     feedbackText.autoresizingMask = [.flexibleWidth, .flexibleHeight]

Надеюсь, это полезно.

Если это TextView, вы можете получить примерные кадры, подобные этой:

    tipsText.textContainer.maximumNumberOfLines = 0
    tipsText.textContainer.heightTracksTextView = true
    tipsText.attributedText = NSAttributedString.init(string:  "You can change the color of a progression tag by long-pressing it on the Progressions", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15) ])
    tipsText.textAlignment = .center
    let size = tipsText.textContainer.size
    tipsText.frame = CGRect(x: tipsCell.bounds.minX,y: self.tipsCell.bounds.minY,width: tipsCell.bounds.width,  height :size.height )
    tipsText.backgroundColor = self.view.tintColor
    tipsText.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    tipsCell.backgroundColor = self.view.tintColor
    tipsCell.addSubview(tipsText)
    tipsText.center = CGPoint(x: tipsCell.bounds.midX, y: tipsCell.bounds.midY)


    feedbackText.textContainer.maximumNumberOfLines = 0
    feedbackText.textContainer.heightTracksTextView = true
    feedbackText.attributedText = NSAttributedString.init(string:  "Feedback is loved! Please email with any issues, comments, ideas, or concerns", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15) ])
    feedbackText.textAlignment = .justified
    let feedbackSize = feedbackText.textContainer.size
    feedbackText.frame = CGRect(x: feedbackCell.bounds.minX,y: self.feedbackCell.bounds.minY,width: feedbackCell.bounds.width,  height :feedbackSize.height )
    feedbackText.backgroundColor = self.view.tintColor
    feedbackText.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    feedbackCell.backgroundColor = self.view.tintColor
    feedbackCell.addSubview(feedbackText)
    feedbackText.center = CGPoint(x: feedbackCell.bounds.midX, y: feedbackCell.bounds.midY)
0 голосов
/ 29 сентября 2018

Я предполагаю, что вы знаете, как использовать пользовательские классы представления.Там пользовательский класс для UITextView;

class VerticallyCenteredTextView: UITextView {
    override var contentSize: CGSize {
        didSet {
            var topCorrection = (bounds.size.height - contentSize.height * zoomScale) / 2.0
            topCorrection = max(0, topCorrection)
            contentInset = UIEdgeInsets(top: topCorrection, left: 0, bottom: 0, right: 0)
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...