๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐ŸŽ iOS/UI

[iOS/UI] Readmore ๊ตฌํ˜„ํ•˜๊ธฐ

by Fomagran ๐Ÿ’ป 2019. 12. 11.
728x90
๋ฐ˜์‘ํ˜•

์ด๋ ‡๊ฒŒ ๋ณ€์ˆ˜๋“ค์„ ์„ ์–ธํ•ด๋†“๊ณ 

class Main: UITableViewController {
    var headerheight = 215
    var headerheights = [Int : Int]()
    var moreless = "more"
    var moreindex = 100
    var morearray = [Int]()

 

์šฐ์„  ์…€ ์•ˆ์˜ ๋ฒ„ํŠผ์— addTarget ํ•ด์ค€๋‹ค. action์•ˆ์—๋Š” ์„ค์ •ํ•ด๋†“์€ ํ•จ์ˆ˜๋ฅผ ์ง‘์–ด๋„ฃ๋Š”๋‹ค.

 cell.morebtn.addTarget(self, action:#selector(Main.more(sender:)) , for: UIControl.Event.touchUpInside)

์„ค์ •ํ•ด๋†“์€ more์ด๋ผ๋Š” ํ•จ์ˆ˜ ์•ˆ์— ๋†’์ด๋ฅผ ์•Œ์•„๋‚ด๋Š” ํ•จ์ˆ˜ heightForView๋ฅผ ์ด์šฉํ•ด ๊ธธ์ด๋ฅผ ์•Œ์•„๋‚ด๊ณ  sender.tag๋ฅผ ์ด์šฉํ•ด ๋ฒ„ํŠผ์˜ index

 @objc func more(sender: UIButton){
        
        moreindex = sender.tag //moreindex๋ฅผ ์„ ํƒํ•œ ํƒœ๊ทธ๋กœ ์„ค์ •ํ•ด์ค€๋‹ค.
        morearray.append(moreindex) //morearray์— ์„ ํƒ๋œ ํƒœ๊ทธ ์ฆ‰ moreindex๋ฅผ ๋„ฃ์–ด์ค€๋‹ค.

    if sender.currentTitle == "more"{ //more์ด๋ผ๊ณ  ์„ค์ •๋˜์–ด์žˆ์œผ๋ฉด
        let Font = UIFont.systemFont(ofSize: 12) //ํฐํŠธํฌ๊ธฐ ์„ธํŒ…
        let height = heightForView(text:"์ž์‹ ์˜ ๊ธ€", font: Font, width: ํ…์ŠคํŠธ๊ฐ€๋กœํฌ๊ธฐ) //text์—
        headerheight = Int(height) //์›๋ž˜ ํ—ค๋”ํ—ค์ดํŠธ๋ฅผ ๋ฐ”๊ฟ”์คŒ
        headerheights.updateValue(headerheight, forKey: moreindex) //๊ทธ๋ฆฌ๊ณ  ํ—ค๋”ํ—ค์ดํŠธ์™€ ์„ ํƒ๋œ moreindex๋ฅผ ๋ฐธ๋ฅ˜ ํ‚ค๊ฐ’์œผ๋กœ ๋„ฃ์–ด์ค€๋‹ค.
        tableView.reloadData() //ํ…Œ์ด๋ธ”๋ทฐ๋ฅผ ์ƒˆ๋กœ๊ณ ์นจํ•ด์คŒ.
        }
        }

๋†’์ด๋ฅผ ์•Œ์•„๋‚ด๋Š” ํ•จ์ˆ˜

func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()

    return label.frame.height
}

ํ—ค๋”๋†’์ด๋ฅผ ์ด์™€๊ฐ™์ด ์„ค์ •ํ•ด์ค€๋‹ค.

 override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        for i in morearray{ //morearray์ค‘์—
            if i == section { //์„น์…˜๊ณผ ๊ฐ™์€์• ๊ฐ€ ์žˆ๋‹ค๋ฉด
                return CGFloat(headerheights[section] ?? 215) //๊ฑฐ๊ธฐ๋Š” ์ •ํ•ด๋†“์€ ํ—ค๋”๋†’์ด๋กœ ๋ฐ”๊ฟ”์ค˜
            }
            
         }
        return 215 //์•„๋‹Œ ๊ฑด ์ž๊ธฐ๊ฐ€ ์ •ํ•ด๋†“์€ ๋†’์ด๋กœ ํ•ด๋†“๋Š”๋‹ค.
        
    }

์ด์™€ ๊ฐ™์ด ์„ค์ •ํ•ด๋†“์œผ๋ฉด ์ด๋ ‡๊ฒŒ ๋œ๋‹ค!

 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€