如何知道此textView中文本的高度?
lazy var textView: UITextView = {
let tv = UITextView()
tv.textColor = .white
tv.translatesAutoresizingMaskIntoConstraints = false
tv.isEditable = false
tv.backgroundColor = .white
tv.text = "Se non vuoi vedere di nuovo questa presentazione clicca sul bottone qui sotto..."
tv.textAlignment = .center
tv.font = UIFont(name: "Avenir-Light", size: 22)
return tv
}()
答案 0 :(得分:11)
您可以像下面这样计算文字高度:
let sizeThatFitsTextView = textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: CGFloat(MAXFLOAT)))
let heightOfText = sizeThatFitsTextView.height
答案 1 :(得分:1)
在我的情况下,我正在计算标签的高度
void ConnectToServer()
{
//... your code
int connectResult = ::connect(sock, (struct sockaddr *)&server, sizeof(server));
if (connectResult >= 0)
{
u_long iMode = 1;
int iResult = ioctlsocket(sock, FIONBIO, &iMode); //Set the socket Non-Blocking
printf("Connected to server!\n");
}
else
{
printf("Not connected to server. Err: %d\n", connectResult);
}
}
int main(){
Connect(); //function to connect with a WiFi network
ConnectToServer();
unsigned long lastSendTime = 0;
unsigned long sendInterval = 200; //send a message every 200 milliseconds
unsigned int nMsgSent = 0;
fd_set write_fd;
while (1){
unsigned long now = milliseconds(); //function to get the time in milliseconds
if ((now - lastSendTime) > sendInterval){
std::string request = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
request += request;
request += std::to_string(nMsgSent);
request += "\n";
FD_ZERO(&write_fd); //Reset the File Descriptor
FD_SET(sock, &write_fd); //Set se File descriptor to the socket.
int result = select(max_sd, NULL, &write_fd, NULL, NULL); //Wait until the socket is ready to write
if (result < 0)
{
iprintf("There was a problem with the sockets reading.\n");
FD_ZERO(&write_fd);
}
int sendResult = ::send(sock, request.c_str(), request.length(), 0);
iprintf("req(%d): %d\n", nMsgSent, sendResult);
nMsgSent++;
lastSendTime = now;
}
}
return 0;
}
答案 2 :(得分:0)
我发现了这个......在我的情况下它起作用了:
func returnStringWidth(font: UIFont, text: String) -> CGSize {
let fontAttributes = [NSFontAttributeName: font]
let size = (text as NSString).size(attributes: fontAttributes)
return size
}