How to use the Segmented Control

本文介绍如何在iOS应用中使用UISegmentedControl组件。通过创建视图控制器项目、添加标签和段控件,设置样式及目标动作,实现当用户选择不同选项时更新UI的功能。

Here is How You Use the Segmented Control [UISegmentedControl]

A segmented control displays a list of options that a user can choose from. Each segment sort of looks like a button; the segments remains “pressed” even after the user lifts his or her finger.

You can detect when a different segment is selected and also what corresponding value in an array (that you supply) is referenced by the selected segment. Here is an example of what a UISegmentedControl looks like:

Here Are the Steps To Use UISegmentedControl

  • Create A View Based XCode Project
  • Add A UILabel To the Controller:
#import "UseSegmentedControlViewController.h"
@implementation UseSegmentedControlViewController
UILabel *label;

- (void)viewDidLoad {
    [super viewDidLoad];

	//Create label
	label = [[UILabel alloc] init];
	label.frame = CGRectMake(10, 10, 300, 40);
	label.textAlignment = UITextAlignmentCenter;
	[self.view addSubview:label];

- (void)dealloc {
     [label release];
     [super dealloc];
}

@end
  • Create An Array:
	NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
  • Create An Instance of UISegmentedControl:
	UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
  • Customize the Control By Setting It’s Properties:
	segmentedControl.frame = CGRectMake(35, 200, 250, 50);
	segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
	segmentedControl.selectedSegmentIndex = 1;
  • Set A Target and Action (The Code That Will Execute When The User Selects A New Segment):
	[segmentedControl addTarget:self
	                     action:@selector(pickOne:)
	           forControlEvents:UIControlEventValueChanged];
  • Add the Segmented Control to the view:
	[self.view addSubview:segmentedControl];
	[segmentedControl release];
  • Implement the Action:
- (void) pickOne:(id)sender{
    UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
    label.text = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
}
  • Release the UILabel in dealloc:
-(void)dealloc{
	[label release];
	[super dealloc];
}

Here Is the Complete Code For the UIViewController:

#import "UseSegmentedControlViewController.h"
@implementation UseSegmentedControlViewController
UILabel *label;

- (void)viewDidLoad {
    [super viewDidLoad];

	//Create label
	label = [[UILabel alloc] init];
	label.frame = CGRectMake(10, 10, 300, 40);
	label.textAlignment = UITextAlignmentCenter;
	[self.view addSubview:label]; 

	//Create the segmented control
	NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
	UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
	segmentedControl.frame = CGRectMake(35, 200, 250, 50);
	segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
	segmentedControl.selectedSegmentIndex = 1;
	[segmentedControl addTarget:self
	                     action:@selector(pickOne:)
	           forControlEvents:UIControlEventValueChanged];
	[self.view addSubview:segmentedControl];
	[segmentedControl release];

}

//Action method executes when user touches the button
- (void) pickOne:(id)sender{
    UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
    label.text = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
} 

- (void)dealloc {
     [label release];
     [super dealloc];
}

@end

Be Sure To Check Out the Header Files In XCode To See All Your Options

You can change the look and feel of the UISegmentedControl by altering the background color. You can use your own images and add/remove segments on the fly.

What Could You Use UISegmented For In Your App?

Let me know in the comments below. Be sure to link to your apps on iTunes if you have them up yet!

\documentclass[12pt]{article} \usepackage{amsmath, amssymb} \usepackage{graphicx} \usepackage{geometry} \usepackage{setspace} \usepackage{caption} \usepackage{titlesec} % 页面设置 \geometry{a4paper, margin=1in} \onehalfspacing % 调整章节标题格式 \titleformat{\section}{\large\bfseries}{\thesection}{1em}{} \titleformat{\subsection}{\normalsize\bfseries}{\thesubsection}{1em}{} % 论文信息 \title{Sieve of Eratosthenes} \author{Zhang Hongwei} \date{December 2, 2025} \begin{document} \maketitle \begin{abstract} This paper describes the Sieve of Eratosthenes, an ancient algorithm for identifying all prime numbers up to a given limit $ n $. The method works by iteratively marking the multiples of each prime starting from 2. We outline its procedure, justify key optimizations, analyze time and space complexity, and compare it with modern variants. A flowchart is included to illustrate the execution process. \end{abstract} \section{Introduction} Finding all primes less than or equal to $ n $ is a basic problem in number theory. While checking individual numbers for primality can be done by trial division, generating many primes efficiently requires a different approach. The Sieve of Eratosthenes, attributed to the Greek mathematician Eratosthenes in the 3rd century BCE, provides a simple and effective solution. It avoids expensive divisibility tests by eliminating composite numbers through multiplication: once a number is identified as prime, all of its multiples are marked as non-prime. Given a positive integer $ n $, the algorithm produces all primes $ \leq n $. Its time complexity is $ O(n \log \log n) $, and it uses $ O(n) $ memory. This makes it practical for $ n $ up to several million on modern computers. \section{Basic Idea} A prime number has no divisors other than 1 and itself. The sieve exploits the fact that every composite number must have at least one prime factor not exceeding its square root. Starting with a list of integers from 2 to $ n $, we proceed as follows: \begin{itemize} \item Mark 2 as prime, then mark all multiples of 2 greater than $ 2^2 = 4 $ as composite. \item Move to the next unmarked number (3), mark it as prime, and eliminate multiples starting from $ 3^2 = 9 $. \item Repeat this process for each new prime $ p $ until $ p > \sqrt{n} $. \end{itemize} After completion, all unmarked numbers are prime. \subsection*{Why start from $ p^2 $?} Any multiple of $ p $ less than $ p^2 $, say $ k \cdot p $ where $ k < p $, would have already been marked when processing smaller primes. For example, $ 6 = 2 \times 3 $ is removed during the pass for 2. Thus, there's no need to revisit these values. \subsection*{Why stop at $ \sqrt{n} $?} If a number $ m \leq n $ is composite, it can be written as $ m = a \cdot b $, with $ 1 < a \leq b $. Then: \[ a^2 \leq a \cdot b = m \leq n \quad \Rightarrow \quad a \leq \sqrt{n}. \] So $ m $ must have a prime factor $ \leq \sqrt{n} $. Therefore, scanning beyond $ \sqrt{n} $ is unnecessary. \section{Implementation Steps} Consider $ n = 100 $. We use a boolean array \texttt{prime[0..100]}, initialized to \texttt{true}. Set \texttt{prime[0]} and \texttt{prime[1]} to \texttt{false}. \begin{enumerate} \item Start with $ p = 2 $. Since \texttt{prime[2]} is true, mark $ 4, 6, 8, \dots, 100 $ as false. \item Next, $ p = 3 $ is unmarked. Mark $ 9, 15, 21, \dots $ (odd multiples $ \geq 9 $). \item $ p = 4 $ is already marked; skip. \item $ p = 5 $ is prime. Mark $ 25, 35, 45, \dots $ \item $ p = 7 $: mark $ 49, 77, 91 $ \item $ p = 11 > \sqrt{100} $, so stop. \end{enumerate} All indices $ i \geq 2 $ where \texttt{prime[i] == true} are prime. \begin{figure}[h!] \centering \includegraphics[width=0.7\linewidth]{Flowchart.jpg} \caption{Flowchart of the Sieve of Eratosthenes algorithm} \label{fig:flowchart} \end{figure} Figure~\ref{fig:flowchart} shows the control flow: initialization, loop over $ p $ from 2 to $ \sqrt{n} $, and marking multiples starting at $ p^2 $. \section{Complexity Analysis} \subsection{Time Usage} For each prime $ p \leq \sqrt{n} $, we mark about $ n/p $ elements. Summing over such $ p $: \[ T(n) \approx n \sum_{\substack{p \leq \sqrt{n} \\ p\ \text{prime}}} \frac{1}{p}. \] It is known from number theory that the sum of reciprocals of primes up to $ x $ grows like $ \log \log x $. So: \[ \sum_{p \leq \sqrt{n}} \frac{1}{p} \sim \log \log \sqrt{n} = \log(\tfrac{1}{2}\log n) = \log \log n + \log \tfrac{1}{2} \approx \log \log n. \] Hence, total time is $ O(n \log \log n) $. \subsection{Memory Requirement} The algorithm requires one boolean value per integer from 0 to $ n $, leading to $ O(n) $ space usage. \section{Variants and Practical Considerations} \begin{table}[h!] \centering \caption{Common methods for generating primes} \label{tab:methods} \begin{tabular}{|l|c|c|l|} \hline Method & Time & Space & Remarks \\ \hline Trial division (single number) & $O(\sqrt{n})$ & $O(1)$ & Simple, slow for batches \\ Standard sieve & $O(n \log \log n)$ & $O(n)$ & Good for $ n \leq 10^7 $ \\ Segmented sieve & $O(n \log \log n)$ & $O(\sqrt{n})$ & Reduces memory usage \\ Linear sieve (Euler) & $O(n)$ & $O(n)$ & Faster in theory, more complex \\ \hline \end{tabular} \end{table} In practice, the standard sieve performs well due to good cache behavior and low constant factors. For very large $ n $, segmented versions divide the range into blocks processed separately. The linear sieve improves asymptotic time by ensuring each composite is crossed off exactly once using its smallest prime factor, but the overhead often negates benefits for moderate inputs. \section{Conclusion} The Sieve of Eratosthenes remains a fundamental tool in algorithm design. Its simplicity allows easy implementation and teaching, while its efficiency supports real-world applications in cryptography, number theory, and data processing. Although newer algorithms exist, the original sieve continues to be relevant—especially when clarity and reliability matter more than marginal speed gains. With minor improvements, it scales well within typical computational limits. \section{References} \begin{thebibliography}{9} \bibitem{knuth} Donald E. Knuth. \textit{The Art of Computer Programming, Volume 2: Seminumerical Algorithms}. 3rd Edition, Addison-Wesley, 1997. ISBN: 0-201-89684-2. (See Section 4.5.4 for discussion of prime number sieves.) \bibitem{hardy} G. H. Hardy and E. M. Wright. \textit{An Introduction to the Theory of Numbers}. 6th Edition, Oxford University Press, 2008. ISBN: 978-0-19-921986-5. (Chapter 1 discusses prime numbers and includes historical notes on Eratosthenes.) \bibitem{pomerance} Carl Pomerance. \newblock “A Tale of Two Sieves.” \newblock \textit{Notices of the American Mathematical Society}, vol.~43, no.~12, pp.~1473–1485, December 1996. Available online: \url{https://www.ams.org/journals/notices/199612/199612FullIssue.pdf#page=1473} \bibitem{crandall} Richard Crandall and Carl Pomerance. \textit{Prime Numbers: A Computational Perspective}. 2nd Edition, Springer, 2005. ISBN: 978-0-387-25282-7. (A detailed treatment of sieve methods including Eratosthenes and segmented variants.) \bibitem{eratosthenes-original} Thomas L. Heath (Ed.). \textit{Greek Mathematical Works, Volume II: From Aristarchus to Pappus}. Harvard University Press (Loeb Classical Library), 1941. ISBN: 978-0-674-99396-7. (Contains surviving fragments and references to Eratosthenes’ work in ancient sources.) \end{thebibliography} \end{document} 修改错误 ,并且增加字数在2000字左右
12-03
/** * @brief Convert a guest physical address payload into iovec entries. * * This function translates a contiguous memory region (starting at 'payload' * with length 'remaining') into one or more iovecs by looking up the virtual * address via gpa_to_vva(). The resulting iovecs are stored in 'iovs', and * 'iov_index' is updated accordingly. * * @param mem Pointer to vhost memory structure for GPA->VVA translation. * @param iovs Array of iovec structures to fill. * @param iov_index Current index in the iovs array (updated on success). * @param payload Guest physical address (GPA) of the data. * @param remaining Total number of bytes left to translate. * @param num_iovs Maximum number of iovecs allowed. * @return 0 on success, -1 on error (e.g., translation failure or overflow). */ static int desc_payload_to_iovs(struct rte_vhost_memory *mem, struct iovec *iovs, uint32_t *iov_index, uintptr_t payload, uint64_t remaining, uint16_t num_iovs) { void *vva; uint64_t len; do { if (*iov_index >= num_iovs) { RDMA_LOG_ERR("MAX_IOVS reached"); return -1; } len = remaining; vva = (void *)(uintptr_t)gpa_to_vva(mem, payload, &len); if (!vva || !len) { RDMA_LOG_ERR("failed to translate desc address."); return -1; } iovs[*iov_index].iov_base = vva; iovs[*iov_index].iov_len = len; payload += len; remaining -= len; (*iov_index)++; } while (remaining); return 0; } /** * @brief Set up iovecs from vring descriptors for a given request. * * Parses the descriptor chain starting at 'req_idx'. Handles both direct and * indirect descriptors. Fills the provided 'iovs' array with valid memory * regions derived from GPA-to-VVA translation. Also counts input/output descriptors. * * @param mem Vhost memory configuration for address translation. * @param vq Virtual queue containing the descriptor ring. * @param req_idx Index of the first descriptor in the chain. * @param iovs Pre-allocated iovec array to populate. * @param num_iovs Size of the iovs array (maximum entries). * @param num_in Output: number of writable (input) descriptors. * @param num_out Output: number of readable (output) descriptors. * @return Number of filled iovecs on success, -1 on error. */ int setup_iovs_from_descs(struct rte_vhost_memory *mem, struct vhost_user_queue *vq, uint16_t req_idx, struct iovec *iovs, uint16_t num_iovs, uint16_t *num_in, uint16_t *num_out) { struct vring_desc *desc = &vq->vring.desc[req_idx]; struct vring_desc *desc_table; uint32_t iovs_idx = 0; uint64_t len; uint16_t in = 0, out = 0; /* Handle indirect descriptors */ if (desc->flags & VRING_DESC_F_INDIRECT) { len = desc->len; desc_table = (struct vring_desc *)(uintptr_t)gpa_to_vva(mem, desc->addr, &len); if (!desc_table || !len) { RDMA_LOG_ERR("failed to translate desc address."); return -1; } assert(len == desc->len); /* Must match original length */ desc = desc_table; /* Now parse the indirect table */ } else { desc_table = vq->vring.desc; /* Use normal descriptor table */ } /* Walk through descriptor chain */ do { if (iovs_idx >= num_iovs) { RDMA_LOG_ERR("MAX_IOVS reached\n"); return -1; } if (desc->flags & VRING_DESC_F_WRITE) { in++; /* Descriptor allows write from device perspective (input) */ } else { out++; /* Descriptor allows read (output) */ } /* Translate payload (address + length) into iovec(s) */ if (desc_payload_to_iovs(mem, iovs, &iovs_idx, desc->addr, desc->len, num_iovs) != 0) { RDMA_LOG_ERR("Failed to convert desc payload to iovs"); return -1; } /* Move to next descriptor in chain */ desc = vhost_rdma_vring_get_next_desc(desc_table, desc); } while (desc != NULL); *num_in = in; *num_out = out; return iovs_idx; } static int vhost_rdma_query_device(struct vhost_rdma_device *dev, CTRL_NO_CMD, struct iovec *out) { struct vhost_rdma_ack_query_device *rsp; CHK_IOVEC(rsp, out); rsp->max_mr_size = dev->attr.max_mr_size; rsp->page_size_cap = dev->attr.page_size_cap; rsp->max_qp_wr = dev->attr.max_qp_wr; rsp->device_cap_flags = dev->attr.device_cap_flags; rsp->max_send_sge = dev->attr.max_send_sge; rsp->max_recv_sge = dev->attr.max_recv_sge; rsp->max_sge_rd = dev->attr.max_sge_rd; rsp->max_cqe = dev->attr.max_cqe; rsp->max_mr = dev->attr.max_mr; rsp->max_pd = dev->attr.max_pd; rsp->max_qp_rd_atom = dev->attr.max_qp_rd_atom; rsp->max_qp_init_rd_atom = dev->attr.max_qp_init_rd_atom; rsp->max_ah = dev->attr.max_ah; rsp->local_ca_ack_delay = dev->attr.local_ca_ack_delay; return 0; } static int vhost_rdma_query_port(__rte_unused struct vhost_rdma_device *dev, CTRL_NO_CMD, struct iovec *out) { struct vhost_rdma_ack_query_port *rsp; CHK_IOVEC(rsp, out); rsp->gid_tbl_len = VHOST_MAX_GID_TBL_LEN; rsp->max_msg_sz = 0x800000; rsp->active_mtu = VHOST_RDMA_IB_MTU_256; rsp->phys_mtu = VHOST_RDMA_IB_MTU_256; rsp->port_cap_flags = 65536UL; rsp->bad_pkey_cntr = 0UL; rsp->phys_state = VHOST_RDMA_IB_PORT_PHYS_STATE_POLLING; rsp->pkey_tbl_len = 1UL; rsp->qkey_viol_cntr = 0UL; rsp->state = VHOST_RDMA_IB_PORT_DOWN; rsp->active_speed = 1UL; rsp->active_width = VHOST_RDMA_IB_WIDTH_1X; rsp->max_mtu = VHOST_RDMA_IB_MTU_4096; return 0; } /* Command handler table declaration */ struct { int (*handler)(struct vhost_rdma_device *dev, struct iovec *in, struct iovec *out); const char *name; /* Name of the command (for logging) */ } cmd_tbl[] = { DEFINE_VIRTIO_RDMA_CMD(VHOST_RDMA_CTRL_ROCE_QUERY_DEVICE, vhost_rdma_query_device), DEFINE_VIRTIO_RDMA_CMD(VHOST_RDMA_CTRL_ROCE_QUERY_PORT, vhost_rdma_query_port), }; /** * @brief Main handler for control virtqueue events. * * Processes incoming requests from the control virtual queue. Waits for kick * notification via eventfd, then processes available descriptor chains. * Each chain contains a header followed by optional input/output data. * Executes corresponding handler based on command ID. * * @param arg Pointer to vhost_rdma_device instance. */ void vhost_rdma_handle_ctrl_vq(void *arg) { struct vhost_rdma_device *dev = arg; struct vhost_rdma_ctrl_hdr *hdr; struct vhost_user_queue *ctrl_vq = &dev->rdma_vqs[0]; struct iovec data_iovs[4]; /* Fixed-size iovec buffer */ struct iovec *in_iovs, *out_iovs; uint16_t desc_idx, num_in, num_out; uint8_t *status; int kick_fd, nbytes, i, in_len; kick_fd = ctrl_vq->vring.kickfd; /* Wait until we get a valid kick (notification) */ do { uint64_t kick_data; nbytes = eventfd_read(kick_fd, &kick_data); if (nbytes < 0) { if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) { continue; /* Retry on transient errors */ } RDMA_LOG_ERR("Failed to read kickfd of ctrl virtq: %s", strerror(errno)); } break; } while (1); /* Process all available requests in the control queue */ while (vhost_rdma_vq_is_avail(ctrl_vq)) { desc_idx = vhost_rdma_vq_get_desc_idx(ctrl_vq); /* Build iovecs from descriptor chain */ if (setup_iovs_from_descs(dev->mem, ctrl_vq, desc_idx, data_iovs, 4, &num_in, &num_out) < 0) { RDMA_LOG_ERR("read from desc failed"); break; } /* Split iovecs into output (device reads) and input (device writes) */ out_iovs = data_iovs; in_iovs = &data_iovs[num_out]; in_len = 0; /* Calculate total input data length */ for (i = 0; i < num_in; i++) { in_len += in_iovs[i].iov_len; } /* First output iovec should contain the control header */ hdr = (struct vhost_rdma_ctrl_hdr *)out_iovs[0].iov_base; status = (uint8_t *)in_iovs[0].iov_base; /* Validate header size */ if (out_iovs[0].iov_len != sizeof(*hdr)) { RDMA_LOG_ERR("invalid header"); *status = VIRTIO_NET_ERR; goto pushq; } /* Check if command ID is within valid range */ if (hdr->cmd >= (sizeof(cmd_tbl) / sizeof(cmd_tbl[0]))) { RDMA_LOG_ERR("unknown cmd %d", hdr->cmd); *status = VIRTIO_NET_ERR; goto pushq; } /* Dispatch command handler; set status based on result */ *status = (cmd_tbl[hdr->cmd].handler(dev, num_out > 1 ? &out_iovs[1] : NULL, num_in > 1 ? &in_iovs[1] : NULL) == 0) ? VIRTIO_NET_OK : VIRTIO_NET_ERR; pushq: /* Log command execution result */ RDMA_LOG_INFO("cmd=%d %s status: %d", hdr->cmd, cmd_tbl[hdr->cmd].name ? cmd_tbl[hdr->cmd].name : "unknown", *status); /* Return used descriptor to the avail ring and notify frontend */ vhost_rdma_queue_push(ctrl_vq, desc_idx, in_len); vhost_rdma_queue_notify(dev->vid, ctrl_vq); } } 这段也是
12-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值