当用户在UITextview中输入一些文本并且我将左,右,底部和上部间距5px约束到UItextView
时,我应该完全混淆我应该在运行时增加tableview单元格高度。我在屏幕上显示但我不使用任何自定义tableviewcell
课程。我想在单个控制器中执行此任务。我只使用XCode 7.3和我的swift版本2.0
@IBOutlet var tedxtviewtableview: UITableView!
var record : NSArray = NSArray()
var hight: CGFloat = 0.0
var newtextstring : NSString = NSString()
我的静态数组。
record = ["I have a UITextView in a custom UITableViewCell. The textview delegate is assigned in the tableviewcell custom class." ,"Textview scrolling is disabled. Text loads into each textview and is multiline. But the text is always clipped because the cell height doesn't change.","I have the following in viewDidLoad of the tableview controller:"," have a UITextView in a custom UITableViewCell. The textview delegate is assigned in the tableviewcell custom class.","Textview scrolling is disabled. Text loads into each textview and is multiline. But the text is always clipped because the cell height doesn't change.","I have the following in viewDidLoad of the tableview controller:","i just give you one link at put place i use label and you can now use your textview and give same constrain that i give in that link and try it so your problem will be solve","I have the following in viewDidLoad of the tableview controller:"];
// tableview delegates method
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return record.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Textviewcell", forIndexPath: indexPath)
let textview: UITextView = (cell.viewWithTag(5) as! UITextView)
textview.scrollEnabled = false
textview.text = record.objectAtIndex(indexPath.row) as? String
Textchange = false
return cell
}
func textViewDidChange(textView: UITextView , Nsindex : NSIndexPath) {
newtextstring = textView.text
self.tedxtviewtableview.beginUpdates()
// This will cause an animated update of
Textchange = true
self.tableView(self.tedxtviewtableview, heightForRowAtIndexPath: Nsindex)
self.tedxtviewtableview.endUpdates()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// 7.1>
if Textchange == true {
hight = self.findHeightForText(newtextstring as String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
return 44 + hight
}else{
hight = self.findHeightForText(self.record.objectAtIndex(indexPath.row) as! String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
return 44 + hight
}
}
func findHeightForText(text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize {
var size = CGSizeZero
if text.isEmpty == false {
let frame = text.boundingRectWithSize(CGSizeMake(widthValue, CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
size = CGSizeMake(frame.size.width, ceil(frame.size.height))
}
return size
}
答案 0 :(得分:1)
取一个变量
var indexPath1 : NSIndexPath = NSIndexPath()
只需在代码中更改此内容
即可func textViewDidChange(textView: UITextView){
let textFieldRowCell = (textView.superview!.superview! as! UITableViewCell)
indexPath1 = self.tedxtviewtableview.indexPathForCell(textFieldRowCell)! //self.tedxtviewtableview.indexPath(forCell: textFieldRowCell)!
newtextstring = textView.text
self.tedxtviewtableview.beginUpdates()
// This will cause an animated update of
//Textchange = true
self.tableView(self.tedxtviewtableview, heightForRowAtIndexPath: indexPath1)
self.tedxtviewtableview.endUpdates()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// 7.1>
if indexPath == indexPath1 {
hight = self.findHeightForText(newtextstring as String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
return 44 + hight
}else{
hight = self.findHeightForText(self.record.objectAtIndex(indexPath.row) as! String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
return 44 + hight
}
}
希望它能运作
答案 1 :(得分:0)
//
// ViewController.swift
// CapturePhotoApp
//
// Created by CS23 on 09/08/17.
// Copyright © 2017 cearsinfotech. All rights reserved.
//
import UIKit
import PinterestLayout
import Stripe
class ViewController: UIViewController ,UICollectionViewDelegate , UICollectionViewDataSource , PinterestLayoutDelegate , UIGestureRecognizerDelegate{
@IBOutlet var MainView: UIView!
@IBOutlet var LightHeaderView: UIView!
@IBOutlet var LightHeaderWidth: NSLayoutConstraint!
@IBOutlet var lblHeaderTitle: UILabel!
var isAppfirst : Bool = false
var isscrolling : Bool = true
var Isopen : Bool = true
var Globaltimer: Timer?
@IBOutlet var TutorialView: UIView!
var ismoredata : Bool = false
var IsFinish = false
var pageCount = 1
var pageSize = 30
var orderType : String = ""
var lastcellindex : Int = 1
var DownloadiMage : UIImageView = UIImageView()
@IBOutlet var GotITWidth: NSLayoutConstraint!
@IBOutlet var btnTutorialgotit: UIButton!
@IBOutlet var ImageCollectionview: UICollectionView!
var arr_img : NSMutableArray = NSMutableArray()
var arr_responseObject : NSMutableArray = NSMutableArray()
var swipeRight : UISwipeGestureRecognizer?
var swipeleft : UISwipeGestureRecognizer?
@IBAction func btn_got_it(_ sender: Any) {
UserDefaults.standard.set(true, forKey: "isFirstView")
UserDefaults.standard.synchronize()
TutorialView.isHidden = true
self.LightHeaderView.alpha = 1.0
UIView.animate(withDuration: 5.0, animations: {
self.LightHeaderView.alpha = 0.0
self.view.layoutIfNeeded()
})
}
var manager = AFHTTPSessionManager()
//MARK:- view life cycle
override func viewDidLoad() {
super.viewDidLoad()
if let isfirst = UserDefaults.standard.object(forKey: "isFirstView") as? Bool {
isAppfirst = isfirst
TutorialView.isHidden = true
GIFProgressHUD .show(withGIFName: "loader", addedTo: self.view, animated: true)
}
else{
TutorialView.isHidden = false
}
btnTutorialgotit.layer.cornerRadius = btnTutorialgotit.frame.size.height / 2
btnTutorialgotit.clipsToBounds = true
LightHeaderView.layer.cornerRadius = LightHeaderView.frame.size.height / 2
LightHeaderView.clipsToBounds = true
LightHeaderView.alpha = 0.0
orderType = "New"
lblHeaderTitle.text = orderType.uppercased()
if UIDevice.current.userInterfaceIdiom == .pad{
ImageCollectionview.scrollPointsPerSecond = 70.0
LightHeaderWidth.constant = 300
GotITWidth.constant = 286
}else{
if UIScreen.main.bounds.width == 375
{
GotITWidth.constant = 230
ImageCollectionview.scrollPointsPerSecond = 70.0
LightHeaderWidth.constant = 180
}
else if UIScreen.main.bounds.width == 414
{
GotITWidth.constant = 286
ImageCollectionview.scrollPointsPerSecond = 90.0
LightHeaderWidth.constant = 200
}
else{
ImageCollectionview.scrollPointsPerSecond = 70.0
}
}
let layout = PinterestLayout()
ImageCollectionview.collectionViewLayout = layout
layout.delegate = self
layout.cellPadding = 3
layout.numberOfColumns = 3
self.callWebserviceAuthorize(pageindex: pageCount, Pagesize: pageSize)
self.ImageCollectionview.addInfiniteScrolling {
if !self.IsFinish{
self.pageCount += 1
self.callWebserviceAuthorize(pageindex: self.pageCount, Pagesize: self.pageSize)
}
}
//pushProductView
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.methodOfReceivedNotification(notification:)), name: Notification.Name("pushProductViewNew"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.openSearchView(notification:)), name: Notification.Name("openSearchView"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.NewDataLoadNotification(notification:)), name: Notification.Name("RemoveGestureNewPhoto"), object: nil)
if AppUtilities.sharedInstance.GetBoolForObserver(str: "NewPhoto") != "1"{
}
if AppUtilities.sharedInstance.isactivemode{
// here open view image
let imageInfo = JTSImageInfo()
imageInfo.imageURL = URL(string: (AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "url") as? String)!)
imageInfo.istrading = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "Istrading") as! String
imageInfo.title = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "title") as? String
imageInfo.altText = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "altText") as? String
imageInfo.thumbnail = AppUtilities.sharedInstance.ImagePrivewDict.object(forKey: "Thumbnail") as? String
let imageViewer = JTSImageViewController(imageInfo: imageInfo, arry: nil, index: 0, mode: .image, backgroundStyle: .blurred)
print(imageInfo)
imageViewer?.show(from: self, transition: .center)
AppUtilities.sharedInstance.isactivemode = false
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setGestureInCollectionview()
AppUtilities.lockOrientation(.all)
UIApplication.shared.statusBarStyle = .default
if Isopen == false{
self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
}
if AppUtilities.sharedInstance.appDelegate.is_Landscape != UIDevice.current.orientation.isLandscape{
self.ImageCollectionview.reloadData()
}
Isopen = true
}
override func viewWillDisappear(_ animated: Bool) {
stopTimer()
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(startTimer), object: nil)
Isopen = false
//NotificationCenter.default.removeObserver(self, name: Notification.Name("RemoveGestureNewPhoto"), object: nil)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if Isopen == false{
// stopSamllTimer()
self.ImageCollectionview .stopScrolling()
self.ImageCollectionview.reloadData()
return
}else{
// stopSamllTimer()
if UIDevice.current.orientation.isLandscape {
AppUtilities.sharedInstance.appDelegate.is_Landscape = true
print("Landscape")
self.ImageCollectionview.reloadData()
} else {
AppUtilities.sharedInstance.appDelegate.is_Landscape = false
print("Portrait")
self.ImageCollectionview.reloadData()
}
self.ImageCollectionview .stopScrolling()
}
}
func NewDataLoadNotification(notification: Notification){
if notification.userInfo != nil{
self.setGestureInCollectionview()
}else{
ImageCollectionview.removeGestureRecognizer(swipeRight!)
ImageCollectionview.removeGestureRecognizer(swipeleft!)
}
}
func openSearchView(notification: Notification){
self.stopTimer()
let dict : NSDictionary = notification.userInfo! as NSDictionary
print(dict)
if Isswipe == true{
self.dismissPopupViewControllerWithanimationType(MJPopupViewAnimationSlideLeftRight)
}
let view: ProductShippingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "ProductShippingViewController"))! as! ProductShippingViewController
view.newphotoasset = String(format: "%@", dict.value(forKey: "Url") as! NSString) as NSString
view.ThumbnailURL = String(format: "%@", dict.value(forKey: "Thumbnail") as! NSURL) as NSString
AppUtilities.lockOrientation(.portrait)
self.navigationController?.pushViewController(view, animated: true)
// let viewController: SearchViewController = (self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController"))! as! SearchViewController
//
// let aObjNavi = UINavigationController(rootViewController: viewController)
// aObjNavi.isNavigationBarHidden = true
// present(aObjNavi, animated: false, completion: nil)
// let viewController: TradingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "TradingViewController"))! as! TradingViewController
//
// let aObjNavi = UINavigationController(rootViewController: viewController)
// aObjNavi.isNavigationBarHidden = true
// present(aObjNavi, animated: false, completion: nil)
}
//MARK:- Gesture Methods
func setGestureInCollectionview(){
swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.SwipeGesture))
swipeRight?.direction = UISwipeGestureRecognizerDirection.right
ImageCollectionview.addGestureRecognizer(swipeRight!)
swipeleft = UISwipeGestureRecognizer(target: self, action: #selector(self.SwipeGesture))
swipeleft?.direction = UISwipeGestureRecognizerDirection.left
ImageCollectionview.addGestureRecognizer(swipeleft!)
}
func SwipeGesture(_ gesture: UIGestureRecognizer) {
self.ImageCollectionview.stopScrolling()
self.stopTimer()
// self.dismiss(animated: false, completion: nil)
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
Isswipe = true
let viewController: TradingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "TradingViewController"))! as! TradingViewController
let aObjNavi = UINavigationController(rootViewController: viewController)
aObjNavi.isNavigationBarHidden = true
present(aObjNavi, animated: false, completion: {
// AppUtilities.sharedInstance.GiveShadowToMainView(View: viewController.MainView!, offset: CGSize(width: 5.0, height: 5.0))
viewController.MainView.frame = CGRect(x: -viewController.view!.frame.size.width, y: 0, width: viewController.view!.frame.size.width, height: viewController.MainView.frame.size.height)
UIView.animate(withDuration: ViewChangeAnimationDuration, delay: 0.0, options: [.curveEaseOut], animations: {
viewController.view!.frame.origin = CGPoint(x: 0, y: 0)
self.view.layoutIfNeeded()
}, completion: { (finished: Bool) in
//AppUtilities.sharedInstance.RemoveShadows(View: viewController.MainView!)
})
})
// self.presentPopupViewController(aObjNavi, animationType: MJPopupViewAnimationSlideLeftRight)
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
//Searching
Isswipe = true
let viewController: SearchViewController = (self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController"))! as! SearchViewController
let aObjNavi = UINavigationController(rootViewController: viewController)
aObjNavi.isNavigationBarHidden = true
present(aObjNavi, animated: false, completion: {
// AppUtilities.sharedInstance.GiveShadowToMainView(View: viewController.view!, offset: CGSize(width: -5.0, height: 5.0))
viewController.view!.frame = CGRect(x: viewController.view!.frame.size.width, y: 0, width: viewController.view!.frame.size.width, height: viewController.view!.frame.size.height)
UIView.animate(withDuration: ViewChangeAnimationDuration, delay: 0.0, options: [.curveEaseIn], animations: {
viewController.view!.frame.origin = CGPoint(x: 0, y: 0)
self.view.layoutIfNeeded()
}, completion: { (finished: Bool) in
// AppUtilities.sharedInstance.RemoveShadows(View: viewController.view!)
})
})
//self.presentPopupViewController(aObjNavi, animationType: MJPopupViewAnimationSlideRightLeft)
default:
break
}
}
}
func methodOfReceivedNotification(notification: Notification){
//Take Action on Notification
print(notification.userInfo!)
if Isswipe == true{
self.dismissPopupViewControllerWithanimationType(MJPopupViewAnimationSlideLeftRight)
}
let dict : NSDictionary = notification.userInfo! as NSDictionary
// let navi : UINavigationController = UINavigationController()
let view: ProductShippingViewController = (self.storyboard?.instantiateViewController(withIdentifier: "ProductShippingViewController"))! as! ProductShippingViewController
view.newphotoasset = String(format: "%@", dict.value(forKey: "Url") as! NSString) as NSString
view.ThumbnailURL = String(format: "%@", dict.value(forKey: "Thumbnail") as! NSURL) as NSString
AppUtilities.lockOrientation(.portrait)
self.navigationController?.pushViewController(view, animated: true)
//navi.pushViewController(view, animated: true)
}
//MARK:- Scrolling Methods
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.ImageCollectionview .stopScrolling()
if !decelerate {
print(decelerate)
stopTimer()
self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
}else{
stopTimer()
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.ImageCollectionview .stopScrolling()
isscrolling = false
if isscrolling == false{
self.perform(#selector(self.startTimer), with: nil, afterDelay: 5.0)
}
}
//MARK:- Timer Init and Close
func startTimer() {
if Globaltimer == nil {
Globaltimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.loop), userInfo: nil, repeats: false)
print("timer start")
}
}
func stopTimer() {
if Globaltimer != nil {
Globaltimer?.invalidate()
Globaltimer = nil
print("timer Stop")
}
}
func loop() {
self.ImageCollectionview .startScrolling()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- Collectionview method
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
if (self.arr_responseObject.count > 0 ){
return self.arr_responseObject.count
}else{
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell",for: indexPath as IndexPath)
let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
let img_view = cell.viewWithTag(20) as! UIImageView
img_view.contentMode = .scaleAspectFit
img_view.downloadImageFrom((dict["urls"] as! NSDictionary)["small"] as! String, contentMode: .scaleAspectFit)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
let arrSend : NSMutableArray = NSMutableArray()
for index in 0..<self.arr_responseObject.count{
let dictTemp : NSDictionary = self.arr_responseObject[index] as! NSDictionary
let imageInfo = JTSImageInfo()
imageInfo.istrading = "0"
imageInfo.imageURL = URL(string: ((dictTemp.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "regular") as! NSString) as String)
imageInfo.title = ((dictTemp.value(forKeyPath: "user") as! NSDictionary).value(forKey: "name") as! NSString) as String!
imageInfo.thumbnail = ((dictTemp.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "thumb") as! NSString) as String!
imageInfo.altText = ((dictTemp.value(forKeyPath: "user") as! NSDictionary).value(forKey: "links") as! NSDictionary).value(forKeyPath: "html") as! String!
arrSend.add(imageInfo)
}
let imageInfo = JTSImageInfo()
AppUtilities.sharedInstance.SetBoolForObserver(str: "NewPhoto", value: "1")
let previewurl = ((dict.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "full") as! NSString) as String
print(previewurl)
let newpreview = previewurl.replacingOccurrences(of: "q=85", with: "q=60&w=1000&h=1000")
print(newpreview)
imageInfo.imageURL = URL(string: newpreview)
imageInfo.title = ((dict.value(forKeyPath: "user") as! NSDictionary).value(forKey: "name") as! NSString) as String!
imageInfo.thumbnail = ((dict.value(forKeyPath: "urls") as! NSDictionary).value(forKeyPath: "full") as! NSString) as String!
imageInfo.altText = ((dict.value(forKeyPath: "user") as! NSDictionary).value(forKey: "links") as! NSDictionary).value(forKeyPath: "html") as! String!
imageInfo.istrading = "0"
let photoid = indexPath.row
let imageViewer = JTSImageViewController(imageInfo: imageInfo, arry: arrSend, index: photoid, mode: .image, backgroundStyle: .blurred)
imageViewer?.show(from: self, transition: .center)
//NotificationCenter.default.post(name: NSNotification.Name("RemoveGestureNewPhoto"), object: nil, userInfo: nil)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
lastcellindex = indexPath.row
if Globaltimer != nil{
self.ImageCollectionview .startScrolling()
}
if self.lastcellindex == self.arr_responseObject.count - 1{
self.ImageCollectionview.triggerInfiniteScrolling()
}
}
func collectionView(collectionView: UICollectionView,
heightForImageAtIndexPath indexPath: IndexPath,
withWidth: CGFloat) -> CGFloat {
let dict : NSDictionary = self.arr_responseObject[indexPath.row] as! NSDictionary
let actualWidth = dict["width"] as? Int ?? 1
let actualHeight = dict["height"] as? Int ?? 1
let actualRatio : Float = Float(actualWidth) / Float(actualHeight)
let framesize : Float = Float(collectionView.frame.size.width - 10) / Float(3)
return CGFloat(framesize / actualRatio)
}
func collectionView(collectionView: UICollectionView,
heightForAnnotationAtIndexPath indexPath: IndexPath,
withWidth: CGFloat) -> CGFloat {
return 0
}
//MARK:- WebService Call
func callWebserviceAuthorize(pageindex : Int , Pagesize : Int){
if AppUtilities.sharedInstance.isNetworkRechable(){
IsFinish = true
let url = "https://api.unsplash.com/photos/?page=\(pageindex)&per_page=\(Pagesize)&order_by=new&client_id=\(APP_ID)"
print(url)
manager.responseSerializer = AFHTTPResponseSerializer()
manager.get(
url,
parameters: nil,
success:
{
(operation, responseObject) in
let json = try? JSONSerialization.jsonObject(with: responseObject as! Data, options: [])
if let arr : NSArray = json as? NSArray
{
if self.pageCount == 1
{
self.LightHeaderView.alpha = 1.0
UIView.animate(withDuration: 5.0, animations: {
self.LightHeaderView.alpha = 0.0
self.view.layoutIfNeeded()
})
self.ImageCollectionview.stopScrolling()
self.arr_responseObject.removeAllObjects()
}else{
}
self.arr_responseObject.addObjects(from: NSMutableArray(array: arr) as! [Any])
print(self.arr_responseObject.value(forKeyPath: "urls") as? NSArray)
self.IsFinish = false
self.ImageCollectionview.infiniteScrollingView.stopAnimating()
self.ImageCollectionview.reloadData()
if self.pageCount == 1
{
if self.isAppfirst != false{
self.perform(#selector(self.startTimer), with: nil, afterDelay: 0.3)
}
}
}
GIFProgressHUD .hide(for: self.view, animated: true)
},
failure:
{
(operation, error) in
print("Error: " + (error?.localizedDescription)!)
self.IsFinish = false
AppUtilities.sharedInstance.showAlert(title: "Error", msg: (error?.localizedDescription)! as NSString)
self.callWebserviceAuthorize(pageindex: self.pageCount, Pagesize: self.pageSize)
self.stopTimer()
})
}else{
AppUtilities.sharedInstance.showAlert(title: "No Internet", msg: "No Internet Connection . please check your Internet.")
}
}
}